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 = ""
userName = "Morgan"
groupName = "Domain Admins"

If IsMember(domainName,userName,groupName) Then
    Wscript.echo "The user '"&userName&"' exists in the group '"&groupName&"'"
    Wscript.echo "The user '"&userName&"' not exists in the group '"&groupName&"'"
End If
' *****************************************************
'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, "-"
   IsMember = CBool(groupListD.Exists(groupName))
End Function
' *****************************************************


No comments:

Post a Comment