Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a better timer output in PowerShell

I have a script which copies some files to a backup storage. And I added a timer to see how much time it would use doing this. I used

$script:start = Get-Date
$start = (Get-Date)
Copy-Item $var0, $var1, $var2 Folders -force -recurse -verbose -Exclude name
$endFulltime = (Get-Date)
"$(($endFulltime-$startFulltime).totalminutes)"

The problem with this is the output. It gives me something like 0,34255234561245 minutes or if I put it in seconds, it just looks the same, but with different numbers. So the problem isn't that it gives me a wrong output; it just looks a bit messy.

Would it be possible to get output like 5 minutes and 43 seconds? Instead of this really long number.

like image 376
Knut Óláfr Roland Avatar asked Jul 04 '26 11:07

Knut Óláfr Roland


2 Answers

Use:

Measure-Command {copy-item $var0, $var1, $var2 Folders -force -recurse -verbose -Exclude name} | select @{n="time";e={$_.Minutes,"Minutes",$_.Seconds,"Seconds",$_.Milliseconds,"Milliseconds" -join " "}}

Measure-Command is to measure the command execution time. Use a hash table with "Select-Object" to customize the output.

The output is in my lab is (I am using the Get-Process cmdlet for testing):

time
----
0 Minutes 0 Seconds 16 Milliseconds

There is a "duration" property too. I will dig into it to see if that can simplify the things.

like image 156
2 revs, 2 users 67%Peter Avatar answered Jul 09 '26 08:07

2 revs, 2 users 67%Peter


Use .ToString() The default "c" "common" format looks pretty fine

function beep {
    # echo "`a" doesn't work in VSCode so I use this
    rundll32 user32.dll,MessageBeep
}

function time() {
    $command = $args -join ' '
    (Measure-Command { Invoke-Expression $command | Out-Default }).ToString()
    beep
}
> time sleep 1.23456
00:00:01.2520795
like image 35
Dimava Avatar answered Jul 09 '26 06:07

Dimava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!