user3022917
user3022917

Reputation: 617

Time Difference in PowerShell 2.0

I need to translate following code to PowerShell 2.0...without success so far.

$startTime = (Get-Date)
<my_script_is_running>
$endTime = (Get-Date)
$ElapsedTime = 'Duration: {0:hh} h {0:mm} min {0:ss} sec' -f ($endTime-$startTime)
Write-Host "$ElapsedTime"

Thanks in advance!

Upvotes: 0

Views: 61

Answers (1)

EylM
EylM

Reputation: 6103

The issue is that PowerShell v2 is not recognizing the standard date/time formats for TimeSpan. (I put Start-Sleep -Seconds 2 to have some timediff).

PowerShell 2 output:

Duration: 00:00:02.0001144 h 00:00:02.0001144 min 00:00:02.0001144 sec

PowerShell 5 output:

Duration: 00 h 00 min 02 sec

You can format "manually" specifing the TimeSpan properties:

$ElapsedTime = ('Duration: {0} h {1} min {2} sec' -f $elapsed.Hours, $elapsed.Minutes, $elapsed.Seconds)

Works in both versions.

Upvotes: 4

Related Questions