PowerShell: Try…Catch does not capture the error

We assume try…Catch will catch errors and we can process exceptions. But Catch only captures Stop Errors. Not all errors are stop errors, that is an error that will stop the script. You can test if the error you want to catch is a stop error by running the script from the command prompt and see if the error stops the script.

Capture non stop Errors

1/ Put a “-ErrorAction Stop” next to your command

2/ Put a “continue” in your catch

E.g

 

Try{

Get-mailbox $myupn -ErrorAction Stop

}

Catch{

$myError=”This is the error” + $_.exception

Write-host $myError

Continue

}

Advertisements