'Get-Job Format-Table with Runtimes of Jobs

I am trying to write a PowerShell 5.1 script for monitoring jobs. I am having a problem writing a proper Get-Job table, the following is what I have.

Get-Job | Format-Table -AutoSize -Property name, state, @{name = 'Runtime'; Expression = {$((get-date)-($_.psbegintime)).ToString('HH:mm')}}

What this code returns is a table of named jobs and states, but does populate the runtime column. It works if I remove the .ToString('HH:mm') from the code but that populates the runtime column with Hour:Minute:Second:Millisecond in this format HH:mm:ss:fffffff. How do I remove the Seconds and Milliseconds part?



Solution 1:[1]

The reason why .ToString(HH:mm) doesn't work is because the result of:

Get-Date - $_.PSBeginTime

Is not a datetime object, it's a timespan object. Calling .ToString(HH:mm) on a timespan object throws the following exception:

MethodInvocationException: Exception calling "ToString" with "1" argument(s): "Input string was not in a correct format."

According to TimeSpan.ToString MS Docs formatting is possible however the format is .ToString('hh\:mm\:ss').

Here you have an example of how to achieve what you're looking for:

$testJobs = 5

$jobs = 1..$testJobs | ForEach-Object {
    Start-Job {
        'Hello from Job {0}' -f $using:_
        Start-Sleep ([random]::new().Next(5,10))
    }
}
 
while($jobs.State -contains 'Running')
{
    Clear-Host
    Get-Job | Format-Table -AutoSize -Property Name, State, @{
        Name = 'Runtime'
        Expression = {
            ([datetime]::Now - $_.PSBeginTime).ToString('hh\:mm\:ss')
            # .ToString('hh\:mm') for Hours and Minutes only.
        }
    }
    Start-Sleep 1
 }
 
$jobs | Receive-Job -Wait -AutoRemoveJob

This answer shows a similar, more developed alternative, using a function to wait for Jobs with progress and a optional TimeOut parameter.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1