在PowerShell中是否有一种简单的方法来计时命令的执行,就像Linux中的'time'命令一样? 我想到了这个:

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

但我想要简单点的,比如

time .\do_something.ps1

当前回答

使用Measure-Command

例子

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

到Out-Host的管道允许您查看命令的输出,即 否则由测量命令消耗。

其他回答

使用Measure-Command

例子

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

到Out-Host的管道允许您查看命令的输出,即 否则由测量命令消耗。

使用秒表和格式化经过的时间:

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 }
(measure-commmand{your command}).totalseconds

例如

(measure-commmand{.\do_something.ps1}).totalseconds

下面是我写的一个函数,它的工作原理类似于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

一种更受PowerShell启发的方式来访问您关心的属性值:

$myCommand = .\do_something.ps1
Measure-Command { Invoke-Expression $myCommand } | Select -ExpandProperty Milliseconds
    4

As Measure-Command返回一个TimeSpan对象。

注意:TimeSpan对象也有TotalMilliseconds作为双变量(如上面我的例子中的4.7322 TotalMilliseconds),这可能对您有用。就像TotalSeconds, TotalDays等。