Measuring Script/Command Execution Time in PowerShell / PowerShell / Measuring Script/Command Execution Time in PowerShell

You can measure the execution time of a command or PowerShell script in several ways.

The easiest way is to simply query the command execution time in the console from the PowerShell command history. The start and end times of the command are contained in the StartExecutionTime and EndExecutionTime attributes:

Get-History | select StartExecutionTime,EndExecutionTime,CommandLine

powershell - get command StartExecutionTime and EndExecutionTime

Get the execution time of the last PowerShell command:

Get-History | select -Last 1 -Property *

You can use the Measure-Command cmdlet to get the total time spent executing all commands in a block (in milliseconds).

This cmdlet takes the command (command block) specified in curly braces, executes it internally, and outputs the time it took to execute as a result.

Measure-Command -Expression {"{0:N2} GB" -f ((gci –force c:\photo –Recurse -ErrorAction SilentlyContinue| measure Length -s).sum / 1Gb)

In this example, the command block is completed in 710 milliseconds.

Measure-Command : get PowerShell script Execution time

You can convert the result to a more convenient time format:

$cmd_time = Measure-Command -Expression {Get-Event}

convert powershell time to string

If you need to determine the execution time in a PowerShell script, you need to get the date value at the beginning of the script and compare it with the date at the end of the script.

$StartTime = (Get-Date)
Start-Sleep -Seconds 10
$EndTime = (Get-Date)
$TotalTime = $EndTime-$StartTime

To get the runtime in a convenient way, you can use the transformation:



'{0:mm} min {0:ss} sec' -f $TotalTime

Script Execution Time in Powershell

You can also use the generic .Net StopWatch class, which is available in all versions of PowerShell (including Windows PowerShell and PowerShell Core). This class allows you to run a timer:

$watch = [System.Diagnostics.Stopwatch]::StartNew()
$watch.Start() # Timer start
# your PowerShell script code
$watch.Stop() # Stopping the timer
Write-Host $watch.Elapsed # Print script execution time

The speed of script execution can be affected by OS load, network connection speed, and other factors. The execution time for the same PowerShell code can vary significantly. If you need to get the predicted execution time for PowerShell code, be sure to measure the script execution time multiple times.

Leave a Reply

Your email address will not be published. Required fields are marked *