Minimalistic Error Handling

by Nov 21, 2017

Error handling does not necessarily have to be complex. It can be as simple as checking whether the last command executed successfully:

# suppress errors by default
$ErrorActionPreference = 'SilentlyContinue'
# if a command runs into an error...
Get-Process -Name zumsel
# ...then $? is $false, and you can exit PowerShell
# with a return value, i.e. 55
if (!$?) { exit 55 }

PowerShell reports back in $? whether the last command encountered an error and returns $false in such as case. Using “exit” and a positive number, you could then bail out, exit your script, and return an exit code to the caller.

Twitter This Tip! ReTweet this Tip!