Wait-Event
等到引發特定事件,再繼續執行。
語法
Default (預設值)
Wait-Event
[[-SourceIdentifier] <String>]
[-Timeout <Int32>]
[<CommonParameters>]
Description
Wait-Event Cmdlet 會暫停執行腳本或函式,直到引發特定事件為止。 偵測到事件時繼續執行。 若要取消等候,請按 CTRL+C。
這項功能提供針對事件進行輪詢的替代方案。 它也可讓您以兩種不同的方式判斷事件的回應:
- 使用事件訂閱的 Action 參數
- 等候事件傳回,然後使用動作回應
範例
範例 1:等候下一個事件
此範例會等候引發的下一個事件。
Wait-Event
範例 2:等候具有指定來源標識碼的事件
此範例會等候引發且具有 ProcessStarted 來源識別碼的下一個事件。
Wait-Event -SourceIdentifier "ProcessStarted"
範例 3:等候定時器經過的事件
此範例會使用 Wait-Event Cmdlet 在設定為 2000 毫秒的定時器上等候定時器事件。
$Timer = New-Object Timers.Timer
$objectEventArgs = @{
InputObject = $Timer
EventName = 'Elapsed'
SourceIdentifier = 'Timer.Elapsed'
}
Register-ObjectEvent @objectEventArgs
$Timer.Interval = 2000
$Timer.Autoreset = $false
$Timer.Enabled = $true
Wait-Event Timer.Elapsed
ComputerName :
RunspaceId : bb560b14-ff43-48d4-b801-5adc31bbc6fb
EventIdentifier : 1
Sender : System.Timers.Timer
SourceEventArgs : System.Timers.ElapsedEventArgs
SourceArgs : {System.Timers.Timer, System.Timers.ElapsedEventArgs}
SourceIdentifier : Timer.Elapsed
TimeGenerated : 4/23/2020 2:30:37 PM
MessageData :
範例 4:在指定的超時之後等候事件
此範例會最多等候 90 秒,以等待具有來源識別碼 ProcessStarted的下一個引發的事件。 如果指定的時間到期,等候就會結束。
Wait-Event -SourceIdentifier "ProcessStarted" -Timeout 90
參數
-SourceIdentifier
指定此 Cmdlet 等候事件的來源標識碼。
根據預設,Wait-Event 等候任何事件。
參數屬性
| 類型: | String |
| 預設值: | None |
| 支援萬用字元: | False |
| 不要顯示: | False |
參數集
(All)
| Position: | 0 |
| 必要: | False |
| 來自管線的值: | False |
| 來自管線按屬性名稱的值: | True |
| 來自剩餘引數的值: | False |
-Timeout
指定 Wait-Event 等候事件發生的時間上限,以秒為單位。 預設值 -1 會無限期等候。 當您提交 Wait-Event 命令時,時間就會開始。
如果超過指定的時間,則等候會結束,並且命令提示字元會返回,即使事件尚未引發也是如此。 不會顯示任何錯誤訊息。
參數屬性
| 類型: | Int32 |
| 預設值: | -1 |
| 支援萬用字元: | False |
| 不要顯示: | False |
| 別名: | TimeoutSec |
參數集
(All)
| Position: | Named |
| 必要: | False |
| 來自管線的值: | False |
| 來自管線按屬性名稱的值: | False |
| 來自剩餘引數的值: | False |
CommonParameters
此 Cmdlet 支援一般參數:-Debug、-ErrorAction、-ErrorVariable、-InformationAction、-InformationVariable、-OutBuffer、-OutVariable、-PipelineVariable、-ProgressAction、-Verbose、-WarningAction 和 -WarningVariable。 如需詳細資訊,請參閱 about_CommonParameters。
輸入
String
輸出
PSEventArgs
備註
事件、事件訂閱和事件佇列只存在於當前會話中。 如果您關閉當前的會話,事件佇列將被丟棄,事件訂閱將被取消。