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…
Comments on this entry are closed.
Function Check-OUExists{
[CmdletBinding()]
Param(#Param Open
[parameter(Mandatory=$true,Helpmessage=”Enter the name of the OU you wish to check”)]
[String]$OUToSeek
)
begin
{
#Puts All OU names into an Array
$AllOUsNames = (Get-ADOrganizationalUnit -Filter *).name
}
Process
{
#Checks if the Array contains the OU being seeked
$Result = $AllOUsNames -contains $OUToSeek
#returns the result
return ,$result
}
End
{
}
}
I think you should call it as Search-ADOU :-). Thanks for posting
Here is a better version here !
https://gallery.technet.microsoft.com/scriptcenter/How-to-verify-if-an-8624e170
Hi, Thanks for commenting. Definitely a good script. But cannot compare with the one given here. Both are intended for different purpose and scope is different.