Powershell checking if OU exist
Try the Exists method, you get back true/false respectively:
[adsi]::Exists("LDAP://OU=test,DC=domain,DC=com")
The following, as suggested by Shay, works great if you're working with clean data.
[string] $Path = 'OU=test,DC=domain,DC=com'
[adsi]::Exists("LDAP://$Path")
Thanks for this great starting point! However, if you're verifying potentially unclean data, you'll get thrown an error. Some examples of possible errors are:
- If the something isn't formatted properly
- (ERR: An invalid dn syntax has been specified)
- If the domain doesn't exist
- (ERR: The server is not operational)
- If the domain won't communicate with you
- (ERR: A referral was returned from the server)
All of these errors should be caught with [System.Management.Automation.RuntimeException]
or you can just leave the catch statement blank to catch all.
Quick Example:
[string] $Path = 'OU=test,DC=domain,DC=com'
try {
$ou_exists = [adsi]::Exists("LDAP://$Path")
} catch {
# If invalid format, error is thrown.
Throw("Supplied Path is invalid.`n$_")
}
if (-not $ou_exists) {
Throw('Supplied Path does not exist.')
} else {
Write-Debug "Path Exists: $Path"
}
More details: http://go.vertigion.com/PowerShell-CheckingOUExists
The problem is the construction of the DirectorySearcher object. To properly set the search root, the DirectorySearcher needs to be constructed using a DirectoryEntry object ([ADSI] type accelerator), whereas you are using a string. When a string is used, the string is used as the LDAP filter and the search root is null, causing the searcher to use the root of the current domain. That is why it looks like it isn't searching the OU you want.
I think you will get the results you are looking for if you do something like the following:
$searchroot = [adsi]"LDAP://OU=USERS BY SITE,DC=Domain,DC=local"
$seek = New-Object System.DirectoryServices.DirectorySearcher($searchroot)
$seek.Filter = "(&(name=$OUToSeek)(objectCategory=organizationalunit))"
... etc ...
Notice that a DirectoryEntry is first constructed, which is then used to construct the DirectorySearcher.