Monday, August 18, 2008

Creating AD objects with Powershell - OUs - Part 1

When you have your management server to RDP into to manage your environment it is a good time to create some objects in your active directory, and it makes sense to start with the basic structure of Organizational Units (OUs).

You need to define the name of the OU and the Distinuguished Name of the domain and pass these in as variables and it would be useful if we checked if the OU already exists so that we can reduce errors we would get if the script was re-run with the same OUname passed to it:-


param([string]$ouname,$DomainDN)

$LDAPPATH = "LDAP://"+ $DomainDN
$search = [System.DirectoryServices.DirectorySearcher]$LDAPPATH
$search.Filter = "(&(name=$ouname)(objectCategory=organizationalunit))"
$result = $search.FindOne()

Next you need to check that the script didn't find an OU with that name then to create the OU, however if the OU already exists, simply record this in the install log:-

if ($result -eq $null) {
$date = get-date -uformat %d/%m/%y" "%H:%M:%S
$date + " Creating OU: " + $ouname>>C:\Install\Logs\ModularADInstall.log

$LDAPCONN = [adsi] $LDAPPATH$newou = $LDAPCONN.Create("OrganizationalUnit",$ouname) $newou.Put("description","AD Auto Deploy")$newou.SetInfo();
$date = get-date -uformat %d/%m/%y" "%H:%M:%S
$date + " Created OU: " + $ou>>C:\Install\Logs\ModularADInstall.log}

else{
$date = get-date -uformat %d/%m/%y" "%H:%M:%S
$date + " OU already exists : " + $ouname>>C:\Install\Logs\ModularADInstall.log}

No comments: