Search code examples
powershellautomationwindows-task-scheduler

How to have a Powershell script notify me when it runs into an error?


I have a Powershell that runs on my company's server every morning (using task scheduler). I have noticed that occasionally it runs into errors and gives an error message when I run it manually, but since I have it run in the morning before anyone gets into the office I currently have no way to see whether or not it ran correctly. Ideally I'd like it to send me an email containing the text from the console log (or anything else providing the error description if anyone has a better idea). I'd also be fine if it just saves the console log into a text file as long as I can check it later. Can anyone help?


Solution

  • Without seeing your script's code it's difficult to say for sure. But, are you aware/familiar with the built-in $Error variable? This might be what you are looking for.

    https://bobcares.com/blog/powershell-error-clear/

    $Error.Count – It checks the number of errors currently on the list.

    $Error[0] – It provides information about the most recent errors.

    $Error.Clear() – It removes all errors from the list.

    You could modify your script to first clear the variable with $Error.Clear() and then run the code and at the end check $Error.Count and if greater than zero check $Error[0] and log the error to a log.

    But again, it all depends on your script's code. If your script is executing external/non-PowerShell commands then I'm not sure if those errors would be captured in this variable.

    If this doesn't get you what you need then have a look at this:

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.host/start-transcript?view=powershell-7.3

    Start-Transcript - This will record everything written to the console to a file.

    Stop-Transcript - This will obviously stop the recording.

    Examples

    PS C:\Users\smith\Documents> Start-Transcript
    Transcript started, output file is C:\Users\smith\Documents\PowerShell_transcript.NEWT.v842NPjk.20221122174909.txt
    PS C:\Users\smith\Documents>
    

    or specify your own path with

    PS C:\Users\smith\Documents> Start-Transcript -Path .\PST.txt
    Transcript started, output file is .\PST.txt
    PS C:\Users\smith\Documents>
    

    Useful Parameters

    -NoClobber will prevent overwriting existing files.

    -Append will append to an existing file.