Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 510
Myrddin Emrys Avatar asked Jul 23 '12 02:07

Myrddin Emrys


People also ask

How do I stop error messages in PowerShell?

If you need to suppress an error, you can use the ErrorAction switch to suppress an error for a single cmdlet or an ErrorAction preference variable to suppress errors globally.

How do I ignore specific errors in PowerShell?

You could use try/catch to only catch (and log/ignore) specific errors and allow all others to be dealt with elsewhere.


3 Answers

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
}
like image 96
Shay Levy Avatar answered Nov 07 '22 20:11

Shay Levy


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
}
like image 11
JPBlanc Avatar answered Nov 07 '22 18:11

JPBlanc


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]

like image 14
Andy Fraley Avatar answered Nov 07 '22 20:11

Andy Fraley