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

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

但我想要简单点的,比如

time .\do_something.ps1

当前回答

到目前为止,所有的答案都没有达到提问者(和我)想要通过在命令行开头添加“time”来计时的愿望。相反,它们都需要将命令包装在括号({})中以构成一个块。下面是一个简短的函数,在Unix上更像时间:

Function time() {
  $command = $args -join ' '
  Measure-Command { Invoke-Expression $command | Out-Default }
}

其他回答

使用Measure-Command

例子

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

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

Yup.

Measure-Command { .\do_something.ps1 }

注意,Measure-Command的一个小缺点是看不到标准输出。

[更新,感谢@JasonMArcher]你可以通过将命令输出输出到一些可写入主机的命令集来修复这个问题,例如Out-Default,这样它就变成:

Measure-Command { .\do_something.ps1 | Out-Default }

查看输出的另一种方法是使用。net Stopwatch类,像这样:

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

到目前为止,所有的答案都没有达到提问者(和我)想要通过在命令行开头添加“time”来计时的愿望。相反,它们都需要将命令包装在括号({})中以构成一个块。下面是一个简短的函数,在Unix上更像时间:

Function time() {
  $command = $args -join ' '
  Measure-Command { Invoke-Expression $command | Out-Default }
}

您还可以从历史记录中获取最后一个命令,并从它的StartExecutionTime中减去它的EndExecutionTime。

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

一种更受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等。