Try ... Catch Error

Not sure, I am missing something here or maybe something very silly I am overlooking…

Why it is not catching the error in the try…catch block?

https://gist.github.com/1edc00b2597faae0fa45bf8ef9d31373

Even inside the script as well.

Put an -ErrorAction in

Try { Test-Connection "localhost1" -Count 1 -ErrorAction stop } Catch { Write-Host "Connection Error" } Finally { Write-Host
"`nTest Complete" }

If the cmdlet you want to catch an error from does not throw a terminating error you have to provide the common parameter -ErrorAction Stop to make it a terminating error.

Try { Test-Connection “localhost1” -Count 1 -ErrorAction Stop } Catch { Write-Host “Connection Error” } Finally { Write-Host “`nTest Complete” }

… should work

Just wanted to also share another common implementation is to add the -Quiet switch which will return a boolean value, like so:

if (Test-Connection "8.8.8.8" -Count 1 -Quiet) {
    'Connection success'
}
else {
    'Connection error'
}

Try/Catch only works with “terminating” errors (statement or script terminating errors).

Yeah, makes sense, I missed it. Thank you so much!