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.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
#requires -version 3.0 #only show results for Enabled jobs Get-ScheduledJob | where Enabled | foreach { Get-Job $_.name -newest 1} | Select Name,ID,State, @{Name="Start";Expression={$_.PSBeginTime}}, @{Name="End";Expression={$_.PSEndTime}}, @{Name="Run";Expression={($_.PSEndTime) - ($_.PSBeginTime)}} | Sort End -Descending
Technically, this is all I really need:
Get-ScheduledJob | where Enabled | foreach { Get-Job $_.name -newest 1}
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.
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.
Remember to run this command elevated (Run as administrator option). It’s user-specific and the admin user and least-privileged user are not the same person. Gets me all the time.
Good catch. I run elevated all the time so sometimes I forget.