#PSTip Validate if an Active Directory Organizational Unit exists or not

For some recent scripting work, I needed to find if an AD OU existed or not from a computer that is not domain-joined. I knew that the System.DirectoryServices.DirectoryEntry class can help but I wasn’t sure how to specify the path.

When I finally figured out, here is how I provided path.

1
New-Object System.DirectoryServices.DirectoryEntry("LDAP://DomainFQDN/OU=OUName,DC=DOMAIN,DC=Suffix",'UserName','Password')

You need to replace the DomainFQDN in the above code sample to something like Contoso.com, OUName with the name of the organizational unit you want to find, Domain with the NETBIOS name like Contoso and finally the Suffix with COM.

1
New-Object System.DirectoryServices.DirectoryEntry("LDAP://Contoso.com/OU=TestUnit,DC=Contoso,DC=com",'administrator','MyP@ssw0rd')

If the object creation succeeds, it will return the object that will have the distinguishedname property set to the path of the OU.

This, of course, assumes that the credentials specified are correct. If the credentials are invalid, you will see an error that the username or password may be wrong.

Share on: