A Better PowerShell Get Scheduled Job Results

Yesterday I posted a quick update on my code to get the most recent scheduled job result in PowerShell. I had been using a simple script. But the more I thought about it, the more I realized I really did need to turn it into a function with more flexibility. When creating a PowerShell based tool you need to think about who might be using it. Even though I only wanted the last result for all enabled jobs, there might be situations where I wanted say the last 2 or 3. Any maybe I wanted to only get results for a specific job. Or maybe all jobs. The bottom line is that I needed more flexibility. Now I have the Get-ScheduledJobResult function.

The function takes parameters that I can pass to Get-ScheduledJob and Get-Job. For the most part the core functionality remains the same: I get the X number of most recent jobs for scheduled jobs. The difference is that now these values are controlled by parameters. The other benefit to my revision is error handling. Before I had a single pipelined expression, but now I use a Try/Catch block to get the scheduled job by name, using * as the default. You’ll also notice I’m using my own error variable. If there is an error, I can handle it more gracefully. I’ll let you test it with a bogus scheduled job name to see what happens.

But perhaps the biggest change is that I define my own object type, based on the Job object.

For every job result insert a new typename. Because I might have multiple objects I need to insert the typename for each one. As I was working on this I originally was inserting my typename into the Microsoft.PowerShell.ScheduledJob.ScheduledJob object. But my custom formatting wasn’t working property, so I found that by selecting all properties, which has the effect of creating a Selected.Microsoft.PowerShell.ScheduledJob.ScheduledJob my changes worked.

Inserting the typename is only part of the process. In the script file that defines the function, I included code to take advantage of Update-TypeData. In PowerShell 3.0 we no longer need to deal with XML files. Now type updates can be done on-the-fly. So instead of creating my custom properties with Select-Object and custom hash tables, I add them as alias properties. I so something similar to create the Run property.

The last part of my revision is to define the default display property set. The effect is that when I run my function, if I don’t specify any other formatting, by default I’ll see the properties I want.

And I still have access to all of the other properties as well.

get-scheduledjob-latest-ogv

Now I have a tool, complete with an alias, with defaults that work for me, but if I need to see something else I can adjust the output based on my parameters. If you want to try this, save the function and type information to the same script file.