CreateADGroup
From Terminal23wiki
This script accepts the group name, active directory location, and an array of the members. Script can be rerun as it checks for existence and can update members. Script will not remove members, however, only add them. Note that BuildLDAPObjectString is used in a few places to build the LDAP string to open the objects or locations.
function CreateADGroup ($strGroupName,$strLocation,$arrMembers)
{
$strGroupCheck = BuildLDAPObjectString $strGroupName $strLocation
$objGroupCheck = [ADSI]$strGroupCheck
if ($objGroupCheck.distinguishedname)
{ }
else
{
$strLDAP = BuildLDAPString $strLocation
$objOU = [ADSI]$strLDAP
$objGroup = $objOU.Create("group", "cn=" + $strGroupName)
$objGroup.Put("sAMAccountName", $strGroupName)
$objGroup.SetInfo()
}
#section to populate group with members, seems easiest to put it here
#and utilize already created objects from above
$strLDAP = BuildLDAPObjectString $strGroupName $strLocation
$objOU = [ADSI]$strLDAP
if ($arrMembers)
{
foreach ($i in $arrMembers)
{
$objOU = [ADSI]$strLDAP
$objFoundUser = ""
$skipbit = "0"
if ($i.length -gt 20)
{ #we search by samaccountname, which has a max length of 20 for user accounts
$i2 = $i.remove(20)
} else { $i2 = $i }
$objSearcher = new-object DirectoryServices.DirectorySearcher([ADSI]"")
$objSearcher.filter = "(&(ObjectClass=User)(sAMAccountName= $i2))"
$objFoundUser = $objSearcher.FindOne()
if ($objFoundUser -eq $null -or $objFoundUser -eq "")
{
$objSearcher = new-object DirectoryServices.DirectorySearcher([ADSI]"")
$objSearcher.filter = "(&(ObjectClass=Group)(sAMAccountName= $i))"
$objFoundUser = $objSearcher.FindOne()
}
if ($objFoundUser)
{
foreach ($member in $objOU.member)
{
if ($member -eq $objFoundUser.properties.distinguishedname){$skipbit = "1"}
}
if ($skipbit -ne "1"){ $objOU.add($objFoundUser.path);$objOU.SetInfo() }
} else { "account/group $i does not exist ($strGroupName group member)" }
}
}
}
