I have a simple Powershell script derived from here which is supposed to exit when a certain condition becomes true (file deleted, modified, etc.)
The script:
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\me\Desktop\folder\"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$continue = $true
$action = {
Write-Host "Action..."
$anexe = "C:\Users\me\Desktop\aprogram.exe"
$params = "-d filename"
Start $anexe $params
$continue = $false
}
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
Register-ObjectEvent $watcher "Deleted" -Action $action
Register-ObjectEvent $watcher "Renamed" -Action $action
while ($continue) {sleep 1}
As you can see, the script is supposed to exit when condition is met (an "action" is taken) since value of continue changes to false
and the loop should then end and the script should exit. However, it keeps going. The loop is endless even when the condition is met.
I have also tried to use exit
to exit out of the powershell script. Does not work either. I tried removing the sleep 1
, however, then it ends up killing my cpu because of the infinite loop without any time gap.
How can I fix it to exit when the file change condition is met?