Gibt es eine einfache Möglichkeit, die Ausführung eines Befehls in PowerShell zeitlich zu steuern, beispielsweise den Befehl 'time' in Linux?
.__ Ich kam dazu:
$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds
Aber ich hätte gerne etwas einfacheres
time .\do_something.ps1
Jep.
Measure-Command { .\do_something.ps1 }
Beachten Sie, dass ein kleiner Nachteil von Measure-Command darin besteht, dass Sie keine Standardausgabe sehen. Wenn Sie die Ausgabe sehen möchten, können Sie das .NET-Stoppuhrobjekt verwenden, z.
$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed
Sie können auch den letzten Befehl aus der Historie abrufen und seine EndExecutionTime
von ihrer StartExecutionTime
abziehen.
.\do_something.ps1
$command = Get-History -Count 1
$command.EndExecutionTime - $command.StartExecutionTime
Measure-Command
verwenden
Beispiel
Measure-Command { <your command here> | Out-Host }
Mit der Pipe an Out-Host
können Sie die Ausgabe des Befehls anzeigen, die ansonsten Measure-Command
verwendet wird.
Einfaches
function time($block) {
$sw = [Diagnostics.Stopwatch]::StartNew()
&$block
$sw.Stop()
$sw.Elapsed
}
dann kann als verwenden
time { .\some_command }
Möglicherweise möchten Sie die Ausgabe optimieren
Ich habe hier eine Funktion geschrieben, die ähnlich wie der Unix-Befehl time
funktioniert:
function time {
Param(
[Parameter(Mandatory=$true)]
[string]$command,
[switch]$quiet = $false
)
$start = Get-Date
try {
if ( -not $quiet ) {
iex $command | Write-Host
} else {
iex $command > $null
}
} finally {
$(Get-Date) - $start
}
}
Quelle: https://Gist.github.com/bender-the-greatest/741f696d965ed9728dc6287bdd336874
Verwenden der Stoppuhr und Formatieren der abgelaufenen Zeit:
Function FormatElapsedTime($ts)
{
$elapsedTime = ""
if ( $ts.Minutes -gt 0 )
{
$elapsedTime = [string]::Format( "{0:00} min. {1:00}.{2:00} sec.", $ts.Minutes, $ts.Seconds, $ts.Milliseconds / 10 );
}
else
{
$elapsedTime = [string]::Format( "{0:00}.{1:00} sec.", $ts.Seconds, $ts.Milliseconds / 10 );
}
if ($ts.Hours -eq 0 -and $ts.Minutes -eq 0 -and $ts.Seconds -eq 0)
{
$elapsedTime = [string]::Format("{0:00} ms.", $ts.Milliseconds);
}
if ($ts.Milliseconds -eq 0)
{
$elapsedTime = [string]::Format("{0} ms", $ts.TotalMilliseconds);
}
return $elapsedTime
}
Function StepTimeBlock($step, $block)
{
Write-Host "`r`n*****"
Write-Host $step
Write-Host "`r`n*****"
$sw = [Diagnostics.Stopwatch]::StartNew()
&$block
$sw.Stop()
$time = $sw.Elapsed
$formatTime = FormatElapsedTime $time
Write-Host "`r`n`t=====> $step took $formatTime"
}
Verwendungsbeispiele
StepTimeBlock ("Publish {0} Reports" -f $Script:ArrayReportsList.Count) {
$Script:ArrayReportsList | % { Publish-Report $WebServiceSSRSRDL $_ $CarpetaReports $CarpetaDataSources $Script:datasourceReport };
}
StepTimeBlock ("My Process") { .\do_something.ps1 }
Measure-Command {echo "Good morning World!" | Write-Host}
Quelle - https://github.com/PowerShell/PowerShell/issues/2289#issuecomment-247793839