Tips on error/crash handling


First time poster so I hope this isn’t considered basic knowledge.

I’m working on a script that I fear will crash from time to time (less and less the better I get at handling errors), but I was wondering if someone here could help me out with a few things.


  1. In my try/catch statements, is there a way to see if an error can be handled or not?
  2. Is it possible to send a warning email from catch or finally? If so, anyone got any tips on where to start? I've tried to find info, but all I can find is how to handle it with robomail.
  3. Is there a heartbeat function somewhere? Is it hard to make a script to listen for a heartbeat (or check timestamp of a log file or whatever)? If #2 is hard to do, I might make another script to monitor
  4. Is there anything I should be aware of when turning my script into a windows task? I currently use "Write-Host", but I guess I should rather use output streams? Any other gotchas you guys are aware of that I might not have to experience myself?


Welcom and you are in the right place. Don Jones has a free resource (or you can donate) on this site:

The Big Book of PowerShell Error Handling

  1. Terminating errors can be handled with Try\Catch, which the above will explain. Most Powershell cmdlets have an ErrorAction, which needs to be set to Stop to terminate the command and throw an exception rather than ignore it.
  2. Yes. try\catch\finally are code blocks, so you can do anything in them such as Send-MailMessage.
  3. The question is heartbeat of what exactly? Checking a date\time stamp is a simple command, Get-Item to check a specific file or Get-ChildItem to search for the latest file in a directory.
  4. As you eluded, there is no visible session to see Write-Host output. You can replace Write-Host with Add-Content to append to a log file for troubleshooting. The only other thing that comes to mind is to ensure that you are testing Powershell in the same context as it will be executing (e.g. if account svc_Account is running the task, open the test Powershell session and run it with that account for validation).

Thanks. I will read the booklet and see what I can learn from it that I don’t already know from c# :slight_smile:

#3: I guess checking the timestamp on the log file will have to suffice. It should update every minute, so if it’s not changing for five minutes I should sound the alarm.

#4: Good tip on the context. Didn’t think of that one :slight_smile: