Hey there!
I have recently played around with an error handling, also using functions.
You can explicitly define the behaviour of the script and how it should handle errors using an $ErrorActionPreference variable. You will typically set it to either of following:
- Continue (default) – in this case an error will be displayed, but the script will attempt to continue
- Stop – the script will stop the execution and report an error
- SilentlyContinue – it will ignore the error (without displaying it) and continue execution
Good. But how about functions, exit (return) codes and error messages? I recently found the cmdlet Write-Error.
Take a look at one example how to do it:
$ErrorActionPreference = "Stop" function test () { Write-Error "Testing failed!" } try { test } catch { $err = $_.Exception.Message Write-Host "An error occured: $err" }
Let me know if it helped you.
Cheers!
Robot(ICT) guy