16

Im having issues getting -ErrorAction SilentlyContinue to work with cmdlet 'Get-ADUser'

This doesn't work, the error is displayed with or without -ErrorAction?

  get-aduser "JSmith" -ErrorVariable Err -ErrorAction SilentlyContinue
  if ($Err){write-host "This is an error!!!!"}

This works (No error is display and silently continues, under the same conditions?

 get-childitem z: -ErrorVariable Err -ErrorAction SilentlyContinue
 if ($Err){write-host "This is an error!!!!"}
user3175140
  • 511
  • 3
  • 6
  • 15

2 Answers2

21

The get is actually performed at the DC by the gateway service, and the error handling doesn't work quite the same. Fortunately Try/Catch does work:

Try { get-aduser "JSmith" } 
  Catch { write-host "This is an error!!!!" }
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • 1
    FYI: Changing to just `catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] ` will ensure that only identity not found exceptions are caught. ps. I've written a proxy function to return null instead of throwing exceptions to avoid having to add try/catch blocks where this cmdlet's used frequently. Code's in a post here: http://stackoverflow.com/questions/37205808/powershell-proxy-function-adding-exception-handling (not great, but it does the job). – JohnLBevan May 13 '16 at 09:17
  • @JohnLBevan - you can also avoid it by using an explicit filter. – mjolinor May 13 '16 at 12:25
  • @mjolinor what is DC? – ameliapond Jun 19 '17 at 08:40
  • 1
    @ameliapond DC = domain controller – mjolinor Jun 19 '17 at 10:35
11

What mjolinor is saying about the explicit filter is the following works:

$Sam = "JSmith"

$userObj = get-aduser -filter {SamAccountName -eq $Sam} -erroraction silentlycontinue

$userObj will be null if the user is not found. This allows the code to address the not found condition with out using the try/catch.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
Garrett
  • 111
  • 1
  • 2