PowerShell 本身并不支持这一点,但如果您需要跟踪多个命令以查看脚本中哪个最慢,您可以使用如下构造:
$commands = @(
'write-host 123',
'write-host 234',
'set-location c:\git',
'write-host 123',
'set-location c:\temp'
)
forEach ($c in $commands){
$stopWatch = Measure-command -Expression {Invoke-Expression $c}
Write-host "The last command [$c] was executed in [$($stopWatch.TotalMilliseconds)]"
}
这将一一执行数组$commands 中的所有命令并在它们上运行Measure-Command,这将返回一个丰富的TimeSpan 对象,其中包含您要使用的TotalMilliseconds 字段。输出如下:
The last command [write-host 123] was executed in [2.3979]
The last command [write-host 234] was executed in [0.031]
The last command [set-location c:\git] was executed in [0.0236]
The last command [write-host 123] was executed in [0.021]
The last command [set-location c:\temp] was executed in [0.0171]
代码的 sn-p 也可以修改为与脚本一起使用,所以如果我们想象我们有一个这样的脚本:
#myCoolScript.ps1
write-host 123
start-sleep -Seconds 2
write-host 234
start-sleep -Seconds 1
set-location c:\git
write-host 123
set-location c:\temp
您可以像这样修改代码以测量每一行:
$commands = get-content .\MyCoolScript.ps1
forEach ($c in $commands){
$stopWatch = Measure-command -Expression {invoke-expression $c}
Write-host "The last command [$c] was executed in [$($stopWatch.TotalMilliseconds)]"
}
这会给出这个输出:
The last command [write-host 123] was executed in [10.1866]
The last command [start-sleep -Seconds 2] was executed in [2000.178]
The last command [write-host 234] was executed in [1.1301]
The last command [start-sleep -Seconds 1] was executed in [999.5883]
The last command [set-location c:\git] was executed in [0.5302]
The last command [write-host 123] was executed in [0.9388]
The last command [set-location c:\temp ] was executed in [0.3985]