Testing Organizational Unit

by May 30, 2017

Provided you have installed the free Microsoft RSAT tools, here is a simple way to check whether an OU exists:

$OUPath = 'OU=TestOU,DC=train,DC=powershell,DC=local'
$exists = $(try { Get-ADOrganizationalUnit -Identity $OUPath -ErrorAction Ignore } catch{}) -ne $null
"$OUPath : $exists"

$exists will be $true or $false, indicating whether the OU was found. Note the use of try/catch error handling: Get-ADOrganizationalUnit can raise terminating errors when the specified OU does not exist, so try/catch is needed to capture these exceptions.

Twitter This Tip! ReTweet this Tip!