我正在設定一個FileSystemWatcher來觀察檔案的變化。這行得通。我還想保持設定它的腳本運行,直到用戶手動終止腳本。這也有效。但是,我還希望在FileSystemWatcher腳本退出(正常或例外)時自動清理事件訂閱。這不起作用,因為事件訂閱是會話的一部分,并且腳本沒有自己的會話。
我嘗試在腳本中創建一個新的會話物件并將其用于觀察程式設定和事件注冊,這似乎在清理腳本終止時的事件訂閱方面做得很好,但它似乎也導致我所有的控制臺活動被吞沒在那個子會話中。
我怎樣才能讓它在腳本退出(正常或例外)時自動清理事件訂閱?(并在保持控制臺輸出可見性的同時這樣做。)
如果背景關系很重要,這是一個簡單的 ZIP 檔案構建腳本。我正在嘗試為其添加“監視模式”,以便當 ZIP 被另一個應用程式更新時,ZIP 會被解壓縮回創建它的檔案夾。因此,此腳本旨在從保持活動狀態的 PowerShell 命令列執行,并且可能在此腳本運行之前和之后用于其他事情。換句話說,Get-EventSubscriber | Unregister-Event除了是腳本用戶必須自己呼叫的另一個命令之外,強大的錘子可能有點過于強大。
這是我的腳本的精簡版:
$watcher = New-Object System.IO.FileSystemWatcher ".", $fileName -Property @{
NotifyFilter = [IO.NotifyFilters]::LastWrite
}
Register-ObjectEvent $watcher -EventName Changed -Action {
Write-Host "File change detected."
# other things, scripts, etc
}
$watcher.EnableRaisingEvents = $true
Write-Host "Press Ctrl C to stop watching the file."
while ($true)
{
if ([Console]::KeyAvailable)
{
$keyInfo = [Console]::ReadKey($true)
if ($keyInfo.Modifiers -eq [ConsoleModifiers]::Control -and $keyInfo.Key -eq [ConsoleKey]::C)
{
Exit
}
}
else
{
Start-Sleep 0.5
}
}
uj5u.com熱心網友回復:
嘗試以下操作:
$watcher = New-Object System.IO.FileSystemWatcher $pwd, $fileName -Property @{
NotifyFilter = [IO.NotifyFilters]::LastWrite
}
# Register with a self-chosen source identifier.
$evtJob = Register-ObjectEvent -SourceIdentifier fileWatcher $watcher -EventName Changed -Action {
Write-Host "File change detected."
# other things, scripts, etc
}
$watcher.EnableRaisingEvents = $true
Write-Host "Press Ctrl C to stop watching the file."
try {
# This blocks execution indefinitely while allowing
# events to be processed in the -Action script block.
# Ctrl-C aborts the script by default, which will execute
# the `finally` block.
Wait-Event -SourceIdentifier fileWatcher
}
finally {
# Clean up the event job, and with it the event subscription.
# Note: If the -Action script block produces output, you
# can collect it with Receive-Job first.
$evtJob | Remove-Job -Force
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454122.html
標籤:powershell events filesystemwatcher
