'Script Name: ldap_primary_group.vbs
'Created By:  Steven Manross
'Version: 1.0
'Description: Queries all the Global and Universal Groups a user is a member of, and determines the Primary Group for the user.

'Many thanks to www.rlmueller.net for the help identifying the "tokengroups" property which make this possible with such a small amount of code

Set objUser = GetObject("LDAP://CN=testuser,OU=someou,DC=somedomain,DC=net")

On Error Resume Next

''use tokengroups if you want the domain local groups as well..
''
''like:
''       Pre-Windows 2000 Compatible Access
''       Users
''       CERTSVC_DCOM_ACCESS

usersid = objUser.objectSid
hexusersid = OctetToHexStr(usersid)
decusersid = HexStrToDecStr(hexusersid)

dom_sid = Left(decusersid,InStrRev(decusersid,"-")-1)


objUser.GetInfoEx Array("tokenGroupsGlobalAndUniversal"), 0
arrbytGroups = objUser.Get("tokenGroupsGlobalAndUniversal")


For j = 0 To UBound(arrbytGroups)
  HexStrSID = OctetToHexStr(arrbytGroups(j))
  Set adgroupobject = GetObject("LDAP://<SID=" & HexStrSID & ">")
  DecStrSID = HexStrToDecStr(HexStrSID)
  if DecStrSid = dom_sid & "-" & objUser.PrimaryGroupID Then  
    'primarygroupid = RID of the group
    WScript.Echo  adgroupobject.samaccountname & " = " & DecStrSID & " (Primary Group)"
  Else
    WScript.Echo  adgroupobject.samaccountname & " = " & DecStrSID
  End If
Next

Function OctetToHexStr(ByVal arrbytOctet)
  On Error Resume Next
  Dim k
  OctetToHexStr = ""
  For k = 1 To Lenb(arrbytOctet)
    OctetToHexStr = OctetToHexStr & Right("0" & Hex(Ascb(Midb(arrbytOctet, k, 1))), 2)
  Next
End Function

Function HexStrToDecStr(strSid)
  On Error Resume Next
  Dim arrbytSid, lngTemp, j 

  ReDim arrbytSid(Len(strSid)/2 - 1) 
  For j = 0 To UBound(arrbytSid) 
    arrbytSid(j) = CInt("&H" & Mid(strSid, 2*j + 1, 2)) 
  Next 

  HexStrToDecStr = "S-" & arrbytSid(0) & "-" & arrbytSid(1) & "-" & arrbytSid(8) 

  lngTemp = arrbytSid(15) 
  lngTemp = lngTemp * 256 + arrbytSid(14) 
  lngTemp = lngTemp * 256 + arrbytSid(13) 
  lngTemp = lngTemp * 256 + arrbytSid(12) 

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) 

  lngTemp = arrbytSid(19) 
  lngTemp = lngTemp * 256 + arrbytSid(18) 
  lngTemp = lngTemp * 256 + arrbytSid(17) 
  lngTemp = lngTemp * 256 + arrbytSid(16) 

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) 

  lngTemp = arrbytSid(23) 
  lngTemp = lngTemp * 256 + arrbytSid(22) 
  lngTemp = lngTemp * 256 + arrbytSid(21) 
  lngTemp = lngTemp * 256 + arrbytSid(20) 

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) 

  lngTemp = arrbytSid(25) 
  lngTemp = lngTemp * 256 + arrbytSid(24) 

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp) 
End Function 
