So I've been doing my error handling in Powershell with Try/Catch so far and whenever an error occurs, it gets written to a log file.
Now how could I handle unexpected errors? Should I just put the whole script code in a Try/Catch block or is there a better method to do this?
Thanks for any help.
2 Answers 2
Yes, there is. You can define a Trap at the top of your script and Log the last error:
trap
{
Write-host $Error[0]
}
1 Comment
$ErrorActionPreference to SilentlyContinue because then my Try/Catch won't work. Is there a way to use Trap without ouput?You are right. When you use the default try/catch(/finally) statements all exception will be trapped in the catch block.
try {
Do-Someting
} catch {
Write-Host "Caught the following error: $($_.Exception.Message)"
} finally {
Write-Host "Finally, we made it!"
}
When you specifically add an exception to catch, you can create specific actions for that exception:
try{
Do-Something
} catch [System.Management.Automation.ItemNotFoundException]{
# catching specific exceptions allows you to have
# custom actions for different types of errors
Write-Host "Caught an ItemNotFoundException: $($_.Exception.Message)" -ForegroundColor Red
} catch {
Write-Host "General exception: $($_.Exception.Message)"
}
Try/Catchis the best approach to handle errors in Powershell. What is the purpose of handling any other "unexpeced" error? Isn't better handling specifically any part of code that actually could generate errors?Get-DateorSet-Variablein aTry/Catchblock makes the script unnecessary long imo. Additionally, those are commands that I've never seen failing to execute so I focus on rather instable parts of my scripts and useTry/Catchthere. Every other error can be an unexpected one since I literally do not expect my scripts to crash there.Get-DateorSet-Variable? How can you usefully handle them?ErrorCollectorin every script I make. The error then gets logged and is also stored in a variable with every other error that occured so far. At the end of every script a mail gets sent to my helpdesk IF at least one error occured or a notification has been set. That's why I also want to log unexpected errors. I just want to get notified of any error that occurs.