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

Viewed 53808

I have a bit of code that looks like this:

if (Get-ADUser $DN -EA SilentlyContinue) {
  # Exists
} else {
  # Doesn't Exist
}

Unfortunately, when Get-ADUser the DN fails to find a user (which is fine, it means the object name is not taken), it throws up and spits out an error. I know it will fail, that's fine, which is why I have an -ErrorAction to SilentlyContinue. Unfortunately it seems to do nothing... I still get barf on the script output. The code works, it's just ugly due to the console spitting out the error.

  • Is there a better way for me to test whether a particular object exists?
  • If not, is there a way to get the ErrorAction to properly be silent?
6 Answers

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]

I like to use the filter parameter because it returns null instead of throwing an exception if the user does not exist.

Example:

$user = Get-ADUser -Filter "SamAccountName -eq '$username'"

if ($user -eq $null)
{
    #User does not exist
}
else
{
    #User exists
}
Related