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

Myrddin Emrys picture Myrddin Emrys · Jul 23, 2012 · Viewed 43.5k times · Source

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?

Answer

Shay Levy picture Shay Levy · Jul 23, 2012

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
}