Blog Archives

PowerShell and Task Scheduler – Working with Exit Code (Last Run Result)


Until we start using PS 3.0, we’re stuck with using Task Scheduler to run our tasks, which is fine, but its hard to tell when a script fails. We then need to create monitoring scripts to monitor the results of the script, or add a lot to the script to get it to handle its own errors.

If you have a monitoring system in place that can monitor schedule tasks, then it would be great to put that to use, and now you can.

In any place you’d normally trap errors and exit, you can do this.


[Environment]::Exit(11)

This will send the Exit Code 11 to Task Scheduler so that a monitoring system can pull the last run result from that task.

There is a ExitCode property in Environment which sets the code on a normal exit

http://msdn.microsoft.com/en-us/library/system.environment.exitcode.aspx

So you can set it and let the script continue if you like.


[Environment]::ExitCode = 11

The other part of this is reading exit codes from task scheduler (maybe you want to make your own monitoring system)

Its real easy if you have the task name, lets say the task is called TestScript


schtasks /query /tn TestScript /v /fo list | ?{$_ -match "Last Result:\s+(.+)"} | %{$matches[1]}

You can remove the TN param and get info for all but then you need to do a little more regex work to pull what you need, but it’s not all that hard.

If you are interested in getting all of them let me know!

Enjoy!

Design a site like this with WordPress.com
Get started