PowerShell - Checking if OU exists
After starting work on a function, I stumbled across the sourced link. I wanted to expand on that post.
That simple method only works well if the LDAP Path is clean. If you’re possibly working with unclean data (or typo the DC structure), you’ll need to catch your errors.
Since DC=domain,DC=com doesn’t exist (or at least isn’t accessible for an LDAP query), I get the following outputted from the above example; which is expected, since I threw the Supplied Path is invalid error (you can handle the error however you want):
Supplied Path is invalid. Exception calling "Exists" with "1" argument(s): "A referral was returned from the server. [...]
In my case, I only work within a particular OU in our Domain, so I’ve made it so my $Path can be abbreviated. Here’s how I handle things:
If the OU=foo,OU=test,DC=domain,DC=com OU exists, the following will be outputed, in the above example:
DEBUG: Path Exists (2): OU=foo,OU=test,DC=domain,DC=com
Hope this helps others out there. Cheers!