OK, so here is the scenario – I was tasked with scripting an action based on group membership. The environment in question does not use nested groups, so I didn’t need to compensate for that (Like Hey, Scripting Guy! already addressed.) I also didn’t want to introduce the possibility of infinite recursion if group A had group B nested in it, which in turn contained group A. This is a real problem I have encountered at a different location that relied on group nesting up to 6 or 7 levels deep… kinda hard to keep track that way. Plus, I wanted to see if I could do it myself.
Now, I could do this in PowerShell, but I’m old fashioned. And so are some of the environments I have to support in my off hours. So, without further ado, here is the code I wrote to make this happen.
' 2016-06-06 JMarcum ' Pass the group to be tested in quotes ' Ex: cscript //nologo test-group.vbs "Domain Users" ' Returns 1 if user is a member of the group, 0 if not ' Variable Declarations Dim WSHNetwork Dim strUserName ' Current user Dim strUserDomain ' Current users domain name Dim strTestGroup ' Group we are testing for - from command line Dim strArg Dim objGroupList Dim objUser Dim objArgs Dim intExists Dim intCount ' Load strTestGroup with the group passed from command line intCount = 1 Set objArgs = WScript.Arguments For Each strArg in objArgs If intCount = 1 Then strTestGroup = strArg Else strTestGroup = strTestGroup & Space(1) & strArg End If intCount = intCount + 1 Next Set objArgs = Nothing ' Wait until the user is really logged in... Set WSHNetwork = WScript.CreateObject("WScript.Network") strUserName = "" While strUserName = "" WScript.Sleep 100 ' 1/10 th of a second strUserName = WSHNetwork.UserName Wend ' Get the users group memberships Set objGroupList = CreateObject("Scripting.Dictionary") objGroupList.CompareMode = vbTextCompare Set objUser = GetObject("WinNT://" _ & WSHNetwork.UserDomain & "/" _ & strUserName & ",user") For Each objGroup In objUser.Groups objGroupList.Add objGroup.Name, " , " Next Set objUser = Nothing ' Test group memberships intExists = 0 ' Default to Not Found If intCount = 2 Then If (CBool(objGroupList.Exists(strTestGroup))) Then intExists = 1 End If Else If (CBool(objGroupList.Exists(Chr(34) & strTestGroup & Chr(34)))) Then intExists = 1 End If End If Set objGroupList = Nothing ' intExists = 1 if user is a member of the group, 0 if not. Return that value as %ERRORLEVEL% WScript.quit intExists