Powershell Measure-Command utility allows you to measure timing for a specific command in your script. By default, this command outputs timespan in multiple formats. In this post, I will show you how to display only seconds part using measure-command.

Measure-Command: How to Time a Code Block or Command

Measure-Command Usage Sample

Measure-Command {
    $AllFiles = Get-ChildItem -Path "D:\\" -Include "*.docx" -Recurse -File | ForEach-Object { $_.FullName }

Example Output:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 36
Milliseconds      : 548
Ticks             : 365485894
TotalDays         : 0.000423016081018519
TotalHours        : 0.0101523859444444
TotalMinutes      : 0.609143156666667
TotalSeconds      : 36.5485894
TotalMilliseconds : 36548.5894

Measure-Command: Display Seconds Only

If you want to get only seconds spent for a specific code block, you can use the pipe to select only seconds property. See it in the example below:

Measure-Command {
    $AllFiles2 = Get-ChildItem -Path "D:\\" -Include "*.docx" -Recurse -File | ForEach-Object { $_.FullName }
} | Select-Object -Property TotalSeconds

This example outputs time spent for your code block in seconds.
If you would like to use timing in a variable, you can also assign its output like this;

Using Timing as a Variable:

$timing = Measure-Command {
    $AllFiles2 = Get-ChildItem -Path "D:\\" -Include "*.docx" -Recurse -File | ForEach-Object { $_.FullName }
} | Select-Object -Property TotalSeconds

Write-Host "It took $($timing.TotalSeconds) to find all files."

Sample Output:

It took 35.1122945 to find all files.

I hope this helps you with your scripts. Enjoy!

Join The Discussion