Get Most Recent PowerShell Scheduled Job Result

I think I’ve posted this before, but in any event even if I did, I’ve tweaked this code a bit. When you create a scheduled job in PowerShell 3.0, by default PowerShell will keep results on disk for the last 32 times the job ran. This can make it a little tricky if you want to check the most recent job. That’s where this short script comes into play.

Technically, this is all I really need:

The command gets all scheduled jobs (which is all you can do anyway) and then filters them keeping only the enabled jobs. Get-Job has a parameter to retrieve the newest job. But unfortunately, the object from Get-ScheduledJob doesn’t have any properties that match with Get-Job. There is an ID property, but they are for two different things. That’s why I resort to piping the filtered objects to ForEach-Object where I can invoke Get-Job using the Name property from the scheduled object job.

The script I use goes a bit further and only selects a few properties I’m interested in. I also calculate a run time for each job. I could create a function out of this, but I simply call the script and typically format the results.
get-scheduledjob-latest2

You may wonder why I didn’t simply include the format command in my script. The reason is that if you include formatting directives, like format table, then there is nothing else you can ever do with the output, except save it to a file or print it. Normally I use a list, but perhaps tomorrow I don’t. Or perhaps I might want to select or sort. If I format the output I can’t do any of those things. My recommendation is to not use any of the format command in your scripts unless you understand the limitation and wish to live with it.

I think the last time I published this I was getting all the scheduled jobs, which seemed kind of silly. But now that I think about it again, perhaps not. Check back tomorrow.

3 thoughts on “Get Most Recent PowerShell Scheduled Job Result”

Comments are closed.