Don’t do that: The following code catch the error with “Exception.Message”:
1 2 3 4 5 6 7 8 9 10 11 |
try { Get-ADUser -Identity AccountNotExist } catch { if ($_.Exception.Message -match 'Cannot find an object with identity') { Write-Warning -Message 'Account not found' } } |
Do that: I prefer to use the exception error in the catch block.
You can have multiple Catch block (each section handles a specific error).
Check the exception error code (Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) and then put that inside the catch block.
The commands inside the try section must have their parameter -ErrorAction set to Stop (or $ErrorActionPreference set to Stop, although not recommended to change this built-in global variable). Doing that, it will turn an error into a terminating error. It is important that the command is processing only one item at a time.
1 2 3 4 5 6 7 8 |
try { Get-ADUser -Identity AccountNotExist -ErrorAction Stop } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { Write-Warning -Message 'Account not found' } |
Tip: To get the last error exception (the first item is the most recent error):
1 2 3 |
$Error[0].Exception.GetType().FullName $Error[0] | Format-List * -Force |
Note: The Try/Catch/Finally construct was introduced since PowerShell v2. In PowerShell v1, the Trap construct was used for error handling.