Hi:
I wonder what’s the common practice for unregistering a registered object in a shell script? My original thought is to wait for user’s prompt in console to terminate, and my code goes like this:
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.IncludeSubdirectories = $false
$targetPath = 'C:\Users\Dell\Pictures\Screenshots'
$watcher.Path = $targetPath
$watcher.EnableRaisingEvents = $true
$action =
{
$path = $event.SourceEventArgs.FullPath
$changetype = $event.SourceEventArgs.ChangeType
#Write-Host "$path was $changetype at $(get-date)"
}
Register-ObjectEvent $watcher "Created" -Action $action
while($true){
$sentinal = read-host "Type no to quit"
if ($sentinal -eq "no"){
get-eventsubscriber -force | unregister-event -force
break
}
}
However, the script works different from my expectation. The action of registered events ( write path was $changetype at $(get-date) to console) was not triggered off until the whole script terminates. I wonder is there a way to resolve this or what’s the common practice for adding an unregister command.
Thanks in advance.