While working on some PS stuff today related to active directory, I came across a need to verify if the given OU(Organization Unit) exists or not. Basically, I am taking OU as input to one of my scripts and would like to validate if that OU exists before doing any processing. After a little bit of research, I found below is quick and useful.
function Test-ADOU { [cmdletbinding()] param( [string] $OuPath ) try { if([ADSI]::Exists("LDAP://$OuPath")) { Write-Host "Given OU exists" } else { Write-Host "OU Not found" } } catch { Write-Host "Error Occurred while querying for the OU" } }
In the above code, the core part that checks for OU existence is [ADSI]::Exists() static method. It returns true if OU exists, otherwise returns false. It will generate appropriate errors if it can not reach the domain you are querying.
Let us see a quick demo to see how it works. My AD structure is like below.
In the below screen first I queried for OldComps OU in the above structure and the the function returned saying “Given OU Exists”. I changed the input OU name to something that doesn’t exists and it returned the not found error message. In the third attempt, I changed the domain name to a non-existing domain.
Hope this helps…