5

I would like to measure multiple times in an automation PowerShell script. I used Get-Date and TotalSeconds. The result looks for example like this: 236.908

How can I get the elapsed time as human readable in minutes and seconds?

$startTime = (Get-Date)
$endTime = (Get-Date)

$ElapsedTime = (($endTime-$startTime).TotalSeconds)

Write-Host "Duration: xx min xx sec"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3022917
  • 579
  • 2
  • 8
  • 20

2 Answers2

11

Use the format operator (-f):

'Duration: {0:mm} min {0:ss} sec' -f ($endTime-$startTime)

or like this, if you need the difference elsewhere as well:

$ElapsedTime = $endTime-$startTime
'Duration: {0:mm} min {0:ss} sec' -f $ElapsedTime
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
4

You can use Measure-Command too:

Measure-Command -Expression {

    # Command 1
    Get-ChildItem

    # Command N
    Get-Process
}

Or like this:

$result = Measure-Command -Expression {

    # Command 1
    Get-ChildItem

    # Command N
    Get-Process
}

$result.ToString()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Esperento57
  • 16,521
  • 3
  • 39
  • 45