How can I use a script to check whether a group exists in Active Directory (AD), and if not, create it?

John Savill

October 23, 2006

1 Min Read
ITPro Today logo in a gray background | ITPro Today

A. The following script, which you can download here, tries to bind to a group and if it doesn't find the group, creates it as a global security group. If you require a universal group instead of a global group, replace the ADS_GROUP_TYPE_GLOBAL_GROUP with ADS_GROUP_TYPE_UNIVERSAL_GROUP in the groupType Put command. You also need to replace the values for domainController, contextpath, and groupName.

    
'Set error handling.  on error resume Next    
Const ADS_GROUP_TYPE_GLOBAL_GROUP = &h2  Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &h8  Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000  Const ADS_PROPERTY_APPEND = 3    
domainController="dalsdc01"  contextpath="ou=Testing,dc=geniant,dc=net"  groupName="testsecgroup"    
'Bind to LDAP server.  set context=getObject("LDAP://" & domainController & "/" & contextpath)  'Error handling and feedback  if err.number0 then           wscript.echo "Error connecting to AD " & err.number, err.description  err.Clear  end if     
set objGroup = GetObject("LDAP://CN="&groupName&","&contextpath)     If Err.Number = "-2147016656" then  'If group was not found  err.clear  'Create the group.  Set objGroup = context.Create("Group","cn="&groupName)  if err.number0 then          wscript.echo "Error creating group " & err.number, err.description  err.Clear  end if  objGroup.Put "sAMAccountName", groupName  objGroup.Put "description", "Testing Group"  objGroup.Put "groupType", ADS_GROUP_TYPE_GLOBAL_GROUP Or _     ADS_GROUP_TYPE_SECURITY_ENABLED  objGroup.setInfo  if err.number0 then          wscript.echo "Error modifying group " & err.number, err.description  err.Clear  end if  end if    
WScript.Quit(0)  

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like