VBScript – Check if current user is a member of a certain group

I found some code to do this out on the net the other day. I’ve modified it a little, and added the part that checks environment variables.

It probably isn’t too efficient, as it creates a new object and then kills it every time the function is called, but it’s fine for my purposes.

‘Error Handling
On Error Resume Next

‘Calls the isMember function with the specified group to see if the current user
‘ is a member of that group.
If isMember(“TypeGroupNameHere”) = “False” Then
       ‘do something
    Else
       ‘do something else
End If

‘ *****************************************************
‘This function checks to see if the passed group name contains the current
‘ user as a member. Returns True or False
Function IsMember(groupName)
    If IsEmpty(groupListD) then
        Set groupListD = CreateObject(“Scripting.Dictionary”)
        groupListD.CompareMode = TextCompare
        ADSPath = EnvString(“userdomain”) & “/” & EnvString(“username”)
        Set userPath = GetObject(“WinNT://” & ADSPath & “,user”)
        For Each listGroup in userPath.Groups
            groupListD.Add listGroup.Name, “-”
        Next
    End if
    IsMember = CBool(groupListD.Exists(groupName))
End Function
‘ *****************************************************

‘ *****************************************************
‘This function returns a particular environment variable’s value.
‘ for example, if you use EnvString(“username”), it would return
‘ the value of %username%.
Function EnvString(variable)
    set objShell = WScript.CreateObject( “WScript.Shell” )
    variable = “%” & variable & “%”
    EnvString = objShell.ExpandEnvironmentStrings(variable)    
    Set objShell = Nothing    
End Function
‘ *****************************************************

This entry was posted in Scripting, SysAdmin, Windows. Bookmark the permalink.

2 Responses to VBScript – Check if current user is a member of a certain group

  1. chrisNo Gravatar says:

    Excellent script, this is exactly what i was looking for. I appreciate your clean scripting style.

    I will call this in a terminal services logon script to map a drive for only users in a specific group.

    Thanks!

  2. Carl BroadyNo Gravatar says:

    Great Blog. I like to play around with HTML code, I try it out on the HTML sandbox site. A great place for trial and error and trouble shooting code. It’s quick too.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>