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.
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.
You could use try/catch to only catch (and log/ignore) specific errors and allow all others to be dealt with elsewhere.
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
}
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
}
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With