Check If Organizational Unit (OU) Exist With PowerShell

In this blog post, I will show you how to check using PowerShell if an organizational unit (OU) exist in Active Directory.

This code is very handy when you need to create an OU In Active Directory using PowerShell but would like to check if the OU exists in the path.

Code

The code can take a parameter when running or by hard coding the OU name.

Make sure, you change the search path in the 4th line to your Ad path.

If the OU exists, the script will exist and display a message.

#param ($newou="OUName") # use with parameter to pass OU name
$newou="NameName" # Type OU name and pass as variable 
Write-Host -ForegroundColor Green "Checking if OU exit in OU=SERVERS,DC=TEST,DC=LOCAL"
$oucheck = [adsi]::Exists("LDAP://OU=$newou,OU=SERVERS,DC=TEST,DC=LOCAL")
if($oucheck -eq "True")
{
$text = "The OU already exist in Active Directory"
Write-Host -ForegroundColor red $text.ToUpper()
exit
}

Processing…
Success! You're on the list.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.