Thursday, 16 July 2015

Check if User is member of AD Group using VBScript

In this article, I am going to write vbscript code to find an Active Directory user is member of an AD group. We can check it by getting user object using GetObject function with ADSI WinNT provider and gets group list from the user object.

VBScript check if user is member of domain group

1. Copy the below example vbscript code and paste it in notepad or a VBScript editor.
2. Save the file with a .vbs extension, for example: CheckMembership.vbs.
3. Replace the domainName,userName and groupName with your own values.
4. Double-click the vbscript file (or Run this file from command window) to check if a user exists in AD group or not.
Option Explicit
Dim domainName,userName,groupName,ADSPath,grouplistD
Dim objUser,objGroup

domainName = "TestDomain.com"
userName = "Morgan"
groupName = "Domain Admins"

If IsMember(domainName,userName,groupName) Then
    Wscript.echo "The user '"&userName&"' exists in the group '"&groupName&"'"
 Else
    Wscript.echo "The user '"&userName&"' not exists in the group '"&groupName&"'"
End If
WScript.quit
 
' *****************************************************
'This function checks if the given AD user is member of the given group.
Function IsMember(domainName,userName,groupName)
   Set groupListD = CreateObject("Scripting.Dictionary")
   groupListD.CompareMode = 1
   ADSPath = domainName & "/" & userName
   Set objUser = GetObject("WinNT://" & ADSPath & ",user")
   For Each objGroup in objUser.Groups
      groupListD.Add objGroup.Name, "-"
   Next
   IsMember = CBool(groupListD.Exists(groupName))
End Function
' *****************************************************

Advertisements
Advertisements

1 comment:

  1. Thanks for great job. I improved function to work even if machine is off the network as the current script fails on that and returns true (if you use on error resume next)

    ' *****************************************************
    'This function checks to see if the passed group name contains the current
    ' user as a member. Returns True or False
    Function IsMember(groupName)
    On error resume next
    If IsEmpty(groupListD) then
    Set groupListD = CreateObject("Scripting.Dictionary")
    groupListD.CompareMode = 1
    ADSPath = EnvString("userdomain") & "/" & EnvString("username")
    BoolReceivedObject = False
    Set userPath = Nothing
    Do Until BoolReceivedObject
    Set userPath = GetObject("WinNT://" & ADSPath & ",user")
    If Err.Number <> 0 Then
    WScript.Sleep 10000
    Err.Clear
    Else
    BoolReceivedObject = True
    End if
    Loop
    For Each listGroup in userPath.Groups
    groupListD.Add listGroup.Name, "-"
    Next
    End if
    IsMember = CBool(groupListD.Exists(groupName))
    End Function
    ' *****************************************************

    ReplyDelete