Powershell — Task Scheduler, Error Handling, and Email

This morning, I created some PowerShell scripts to perform basic tasks. Nothing fancy by all means. The scripts will be run from the Task Scheduler so I needed to be aware of errors.

After a bit of research, I discovered how to schedule a script from the Task Scheduler, capture errors, and send an email.

Let’s start with the Task Scheduler. If you haven’t used Windows Task Scheduler, it is simple. If you don’t like it, there are free alternatives. System Scheduler by Splinterware is a nice alternative.

Start by opening the Task Scheduler.
Create a basic task.
Enter a name that is summarizes the task.
Select the frequency for the task (Daily, Weekly, one time, etc.).
Check the box for Start a program.
On the Action window, enter powershell.exe under Program/Script.
In the Add arguments section, enter -ExecutionPolicy Bypass C:\psscripts\hereismyscript.ps1
One the last window, be sure to check the box to show Advanced Properties after save.
When the window is opened, check the box (lower left) for running with highest privileges. 
Save the changes.

That’s it, your powershell script will run at the designated time(s).

Error handling was a different story. I wanted something simple. A try/catch is suggested but I didn’t worry about it. Remember, simple. And simple is what I got. The parameter “-ErrorVariable” was the solution for me.

Here are some links to sites that helped me learn the error handling.

Here is my script for detecting an error. An extension to the existing line of code and a new line. There are other solutions that are more robust.

Copy-Item -Path ‘My Source File’ -Destination ‘\\UNC\Path\’ -ErrorVariable ProcessError
$ProcessError.Count;

Now I know there is an error. The next step is to be alerted to the error. That is where the Send-MailMessage command comes in handy. An if statement and one line of code to send the email.

if($ProcessError) {
Send-MailMessage -To sendtome@email.com -from sendfromme@email.com -Subject “Error copying my source file to unc path” -SmtpServer smtp.email.com
}

Some links to help learn emailing in PowerShell.

Here is my entire script. It is basic, I know but it gives a good example.

Copy-Item -Path ‘My Source File’ -Destination ‘\\UNC\Path\’ -ErrorVariable ProcessError
$ProcessError.Count;

if($ProcessError) {
Send-MailMessage -To sendtome@email.com -from sendfromme@email.com -Subject “Error copying my source file to unc path” -SmtpServer smtp.email.com
}

Keep in mind, learning is power.