I have a script that creates domain local and global groups based off of server names in multiple domains in a forest. It works fine, except that if it tries to create a group that already exists it will error out. I just need to verify that the group doesn't exist before it does the "put" to create the group. This is what I have now:
I'm sure I can create a function to do a query to AD to return all of the groups with the name that I am checking for (strAdmingGlobalName or strAdminDomainLocalName), and if the collection returned is empty then I know that it doesn't exist. But is there a more elegant way to do this in the code above?
Code:
For Each strComputer in arrComputers
' Create Global group in AD
Set objContainer = GetObject("LDAP://" & strGlobalContainer)
strAdminGlobalName = strComputer & "_Admin_Access_AMR_GG"
Set objGroupGG = objContainer.Create("group", "cn=" & strAdminGlobalName)
objGroupGG.Put "sAMAccountName", strAdminGlobalName
objGroupGG.Put "groupType", ADS_GROUP_TYPE_Global_GROUP Or ADS_GROUP_TYPE_SECURITY_ENABLED
objGroupGG.SetInfo
' Create Domain Local group in AD
Set objContainer = GetObject("LDAP://" & strDomainLocalContainer & "," & objRootDSE.DistinguishedName)
strAdminDomainLocalName = strComputer & "_Admin_Access_AMR_DL"
Set objGroupDL = objContainer.Create("group", "cn=" & strAdminDomainLocalName)
objGroupDL.Put "sAMAccountName", strAdminDomainLocalName
objGroupDL.Put "groupType", ADS_GROUP_TYPE_LOCAL_GROUP Or ADS_GROUP_TYPE_SECURITY_ENABLED
objGroupDL.SetInfo
If intCrossForest = 1 Then
' Get SID of Global Group from domain.local
intUserSID = fnGet_HexString(objGroupGG.ObjectSID)
' Make Global group a member of the Domain Local group.
objGroupDL.Add("LDAP://<SID=" & intUserSID & ">")
Else
' Make Global group a member of the Domain Local group.
objGroupDL.Add(objGroupGG.ADsPath)
End If
' Tries to ping server and add Domain Local group to the Local Administrators group on the server
If IsPingable(strComputer, "", "") Then
Wscript.Echo strComputer & " appears to be online, attempting to add Domain Local group to server local Administrators group."
Set objServerLocalAdminGroup = GetObject("WinNT://" & strComputer & "/Administrators")
Set objUser = GetObject("WinNT://" & strAdminDomainLocalName & "@" & strDomain)
objServerLocalAdminGroup.Add(objUser.ADsPath)
Else
strOffline = strOffline & vbCr & strComputer
End If
Next
I'm sure I can create a function to do a query to AD to return all of the groups with the name that I am checking for (strAdmingGlobalName or strAdminDomainLocalName), and if the collection returned is empty then I know that it doesn't exist. But is there a more elegant way to do this in the code above?