Checking for the existence of an AD object; how do I avoid an ugly error message? Checking for the existence of an AD object; how do I avoid an ugly error message? powershell powershell

Checking for the existence of an AD object; how do I avoid an ugly error message?


The only way I have found to be working without spitting an error is with the filter parameter:

if (Get-ADUser -Filter {distinguishedName -eq $DN} ) {  # Exists} else {  # Doesn't Exist}


You want to catch the exception of the object not being found, but you still want to fail for other reasons like access denied and such, so you need to specify the exact exception to catch.

Try{  Get-ADUser $DN -ErrorAction Stop  # Do stuff if found}Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{   # Do stuff if not found}

To determine the exception type to catch in other use cases, cause an exception and then do:

$Error[0].Exception.GetType().FullName

The output of that goes into: catch [insert exception type here]


It's an exception, you can just try to catch it like this :

$user = $(try {Get-ADUser $DN} catch {$null})if ($user -ne $null) {  # Exists} else {  # Doesn't Exist}