Creating AD security groups
Continuing my AD excursion for a while. I saw a forum post about creating AD groups and came up with this function
function new-securitygroup {
[CmdletBinding()]
param (
[string]$name,
[string]$ou,
[parameter(ParameterSetName="U")]
[switch]$universal,
[parameter(ParameterSetName="G")]
[switch]$global,
[parameter(ParameterSetName="DL")]
[switch]$domainlocal
)
$rootdse = [ADSI]""
$adpath = "$ou,$($rootdse.distinguishedName)"
Write-Debug $adpath
# set constants for group types
$globalgroup = 0x00000002
$domainlocalgroup = 0x00000004
$security = 0x80000000
$universalgroup = 0x00000008
$targetou = [ADSI]"LDAP://$adpath"
switch ($psCmdlet.ParameterSetName) {
"DL" {
$grouptype1 = $security -bor $universalgroup
$grouptype2 = $security -bor $domainlocalgroup}
"G" {$grouptype = $security -bor $globalgroup }
"U" {$grouptype = $security -bor $universalgroup }
default {Write-Host "Error!!! Should not be here" }
}
$newgroup = $targetou.Create("Group", "cn=$name")
$newgroup.SetInfo()
if ($domainlocal) {
$newgroup.GroupType = $grouptype1
$newgroup.SetInfo()
$newgroup.GroupType = $grouptype2
$newgroup.SetInfo()
}
else {
$newgroup.GroupType = $grouptype
$newgroup.SetInfo()
}
$newgroup.samAccountname = $name
$newgroup.SetInfo()
}
Parameter sets are used to keep the group types mutually exclusive
Note how we have to change the group type to universal before changing to domain local
Examples of use are as follows
new-securitygroup -name test-g -ou "ou=All Groups" -global
new-securitygroup -name test-u -ou "ou=All Groups" -universal
new-securitygroup -name test-dl -ou "ou=All Groups" –domainlocal
Trying to change the group type and/or the samaccountname as you create the group will generate an error