Measure-Command
测量运行脚本块和 cmdlet 所需的时间。
Measure-Command
[-InputObject <PSObject>]
[-Expression] <ScriptBlock>
[<CommonParameters>]
Measure-Command
cmdlet 在内部运行脚本块或 cmdlet,将作的执行时间超时,并返回执行时间。
备注
脚本块由 Measure-Command
当前作用域中运行,而不是子作用域运行。
此示例测量运行获取 Windows PowerShell 事件日志中的事件的 Get-EventLog
命令所需的时间。
Measure-Command { Get-EventLog "windows powershell" }
第一个命令测量处理递归 Get-ChildItem
命令所需的时间,该命令使用 Path 参数仅获取 C:\Windows
目录中及其子目录中的 .txt
文件。
第二个命令测量处理使用提供程序特定的 Filter 参数的递归 Get-ChildItem
命令所需的时间。
这些命令显示在 PowerShell 命令中使用提供程序特定的筛选器的值。
Measure-Command { Get-ChildItem -Path C:\Windows\*.txt -Recurse }
Days : 0
Hours : 0
Minutes : 0
Seconds : 8
Milliseconds : 618
Ticks : 86182763
TotalDays : 9.9748568287037E-05
TotalHours : 0.00239396563888889
TotalMinutes : 0.143637938333333
TotalSeconds : 8.6182763
TotalMilliseconds : 8618.2763
Measure-Command {Get-ChildItem C:\Windows -Filter "*.txt" -Recurse}
Days : 0
Hours : 0
Minutes : 0
Seconds : 1
Milliseconds : 140
Ticks : 11409189
TotalDays : 1.32050798611111E-05
TotalHours : 0.000316921916666667
TotalMinutes : 0.019015315
TotalSeconds : 1.1409189
TotalMilliseconds : 1140.9189
传递给 Measure-Command
的对象可用于传递给 Expression 参数的脚本块。 脚本块针对管道上的每个对象执行一次。
# Perform a simple operation to demonstrate the InputObject parameter
# Note that no output is displayed.
10, 20, 50 | Measure-Command -Expression { for ($i=0; $i -lt $_; $i++) {$i} }
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 12
Ticks : 122672
TotalDays : 1.41981481481481E-07
TotalHours : 3.40755555555556E-06
TotalMinutes : 0.000204453333333333
TotalSeconds : 0.0122672
TotalMilliseconds : 12.2672
若要在 Measure-Command
中显示表达式的输出,可以使用管道 Out-Default
。
# Perform the same operation as above adding Out-Default to every execution.
# This will show that the ScriptBlock is in fact executing for every item.
10, 20, 50 | Measure-Command -Expression {for ($i=0; $i -lt $_; $i++) {$i}; "$($_)" | Out-Default }
10
20
50
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 11
Ticks : 113745
TotalDays : 1.31649305555556E-07
TotalHours : 3.15958333333333E-06
TotalMinutes : 0.000189575
TotalSeconds : 0.0113745
TotalMilliseconds : 11.3745
Measure-Command
在当前作用域中运行脚本块,因此脚本块可以修改当前作用域中的值。 若要避免更改当前范围,必须将脚本块包装在大括号({}
)中,并使用调用运算符(&
)在子作用域中执行块。
$foo = 'Value 1'
$null = Measure-Command { $foo = 'Value 2' }
$foo
$null = Measure-Command { & { $foo = 'Value 3' } }
$foo
Value 2
Value 2
有关调用运算符的详细信息,请参阅 about_Operators。
指定正在计时的表达式。 将表达式括在大括号({}
)。
类型: | ScriptBlock |
Position: | 0 |
默认值: | None |
必需: | True |
接受管道输入: | False |
接受通配符: | False |
绑定到 InputObject 参数的对象是传递给 Expression 参数的脚本块的可选输入。 在脚本块中,$_
可用于引用管道中的当前对象。
类型: | PSObject |
Position: | Named |
默认值: | None |
必需: | False |
接受管道输入: | True |
接受通配符: | False |
可以通过管道将对象传递给此 cmdlet。
此 cmdlet 返回表示结果的时间跨度对象。