Measure-Command
測量執行腳本區塊和 Cmdlet 所需的時間。
語法
Measure-Command
[-InputObject <PSObject>]
[-Expression] <ScriptBlock>
[<CommonParameters>]
Description
Measure-Command
Cmdlet 會在內部執行腳本區塊或 Cmdlet、逾時執行作業,並傳回運行時間。
注意
Measure-Command
在目前範圍中執行的腳本區塊,而不是子範圍。
範例
範例 1:測量命令
此範例會測量執行取得 Windows PowerShell 事件記錄檔中事件 Get-EventLog
命令所需的時間。
Measure-Command { Get-EventLog "windows powershell" }
範例 2:比較來自 Measure-Command 的兩個輸出
第一個命令會測量處理遞歸 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
範例 3:Measure-Command 的管線輸入
傳送至 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
範例 4:顯示已測量命令的輸出
若要在 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
範例 5:測量子範圍中的執行
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。
參數
-Expression
指定正在計時的表達式。 以大括弧括住表達式({}
)。
類型: | ScriptBlock |
Position: | 0 |
預設值: | None |
必要: | True |
接受管線輸入: | False |
接受萬用字元: | False |
-InputObject
系結至 InputObject 參數的對像是傳遞至 Expression 參數之腳本區塊的選擇性輸入。 在腳本區塊內,$_
可用來參考管線中的目前物件。
類型: | PSObject |
Position: | Named |
預設值: | None |
必要: | False |
接受管線輸入: | True |
接受萬用字元: | False |
輸入
您可以使用管線將 物件傳送至這個 Cmdlet。
輸出
此 Cmdlet 會傳回代表結果的時間範圍物件。