Use PowerShell ADSI to Create an AD Group

Other Posts in this Series:

This post provides a simple example of how we can use PowerShell ADSI to create an AD group.

$adGroupType = @{
Global      = 0x00000002
DomainLocal = 0x00000004
Universal   = 0x00000008
Security    = 0x80000000
}
#OU containing the AD group
$adGroupOU="OU=Application,OU=Groups,DC=alkanesolutions,DC=co,DC=uk"
#AD group name
$addADGroupName = "alkane_group"
#Full distinguished name of AD group		
$distinguishedName = "CN=$addADGroupName,$adGroupOU"
#check if exists
$group = ([ADSISearcher] "(distinguishedName=$distinguishedName)").FindOne()
if ($group -eq $null)
{	
#group doesn't exist
#get OU
$adsiADGroup = [adsi]("LDAP://$adGroupOU")
#create group in OU
$newGroup = $adsiADGroup.Create('group', "CN=$addADGroupName")
#Make it a global security group
$newGroup.put('grouptype',($adGroupType.Global -bor $adGroupType.Security))
$newGroup.put('samaccountname',$addADGroupName)
$newGroup.SetInfo()	
}