在PowerShell中执行命令的执行

有没有一种简单的方法来在PowerShell中执行命令,例如Linux中的“time”命令?
我想出了这个:

$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds 

但是我想要更简单的东西

 time .\do_something.ps1 

对。

 Measure-Command { .\do_something.ps1 } 

请注意,Measure-Command的一个小缺点是,您看不到stdout输出。 如果你想看到输出,那么你可以使用.NET秒表对象,例如:

 $sw = [Diagnostics.Stopwatch]::StartNew() .\do_something.ps1 $sw.Stop() $sw.Elapsed 

您也可以从历史logging中获取最后一个命令,并从StartExecutionTime减去EndExecutionTime

 .\do_something.ps1 $command = Get-History -Count 1 $command.EndExecutionTime - $command.StartExecutionTime 

使用Measure-Command

 Measure-Command { <your command here> | Out-Host } 

Out-Host的pipe道允许您查看命令的输出,否则该命令会被Measure-Command消耗。

Simples

 function time($block) { $sw = [Diagnostics.Stopwatch]::StartNew() &$block $sw.Stop() $sw.Elapsed } 

然后可以使用

 time { .\some_command } 

你可能想要调整输出

使用秒表和格式化已用时间:

 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" } 

用法示例

 StepTimeBlock ("Publish {0} Reports" -f $Script:ArrayReportsList.Count) { $Script:ArrayReportsList | % { Publish-Report $WebServiceSSRSRDL $_ $CarpetaReports $CarpetaDataSources $Script:datasourceReport }; } StepTimeBlock ("My Process") { .\do_something.ps1 } 

这是我写的一个函数,它和Unix time命令类似:

 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 } } 

资料来源: https : //gist.github.com/bender-the-greatest/741f696d965ed9728dc6287bdd336874