我有一個作業正常的片段。它注冊一個物件事件如下(片段):
Register-ObjectEvent $Watcher -EventName Created -SourceIdentifier FileCreated -Action {
它作業正常,但我似乎無法讓腳本完全停止和取消注冊。當我使用“正常”方法來停止代碼(如下所列)時,當我重新運行代碼(通過 F5)時,出現錯誤:
Register-ObjectEvent : Cannot subscribe to the specified event. A subscriber with the source identifier 'FileCreated' already exists.
我可以取消注冊(到目前為止)的唯一方法是終止 powershell.exe 行程,這也會終止 VSCode 中的 powershell 運行時間(拋出錯誤,強制手動重啟)。
我按 F5 啟動代碼
為了停止代碼,我嘗試過:
- Shift-F5
- Ctrl-C(在 powershell 終端區域)
除上述情況外,沒有任何作用。
我錯過了什么?
uj5u.com熱心網友回復:
僅出于除錯目的,您經常強制停止腳本,有 2 個選項。要么unregister-Event手動運行該行,以便取消注冊該事件,要么在腳本的頂部附近添加類似的內容。(至少在 之前Register-ObjectEvent)
Unregister-Event -SourceIdentifier FileCreated -EA 0
-EA 0與-ErrorAction SilentlyContinue當您在新會話中并且該事件從未注冊過時相同,并且將防止腳本拋出錯誤。
注意:這不應出現在您的生產腳本中,僅用作除錯幫助。(如果你想把它放在手邊,我會說至少在腳本的生產版本上注釋掉它)
不過,您的腳本的生產版本應該Unregister-Event正確實施,更類似于:
$FileWatcherReg = @{
InputObject = $Watcher
EventName = 'Created'
SourceIdentifier = 'FileCreated'
MessageData = @{WatchQueue = $WatchQueue; Timer = $WatchTimer }
Action = {
if ($null -ne $event) {
Write-Host "Path: $($Event.SourceArgs.FullPath) - ($($Event.Timegenerated))"
}
}
}
Register-ObjectEvent @FileWatcherReg
while ($true) {
Start-Sleep -Milliseconds 100
# Logic to exit the loop at some point.
}
# Exit script logic ...
Unregister-Event -SourceIdentifier FileCreated
uj5u.com熱心網友回復:
與上面 Sage 的示例類似,是這個更大的示例。它清楚地構造了事件,并顯示了如何通過保持腳本運行,然后取消腳本,這將觸發清理塊。
因此,對于這種方法,有些話要說。(但是,我繼續將整個 Register-ObjectEvent 視為一種 TSR ......您的代碼保持駐留......永遠......等待相關事件......)
示例:https : //community.idera.com/database-tools/powershell/powertips/b/tips/posts/using-filesystemwatcher-correctly-part-2#
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395662.html
上一篇:字串中有空格,但我無法在powershell中拆分它
下一篇:匯入密碼-憑證
