itnifl
asked on
IO.FileSystemWatcher dies when used in Powershell
Creating the watcher:
Then registering events:
So this sets up a file system watcher in PowerShell, and I can do stuff based on the events that happen when files are created, changed, and so on. This is all nice, but what happens is that when the script runs long enough, the $FileSystemWatcher stops after some time. Like it is being garbage collected or something (guesswork). When retrieving the $FileSystemWatcher object and the named events, they tell me nothing new. Also there are no errors to be found anywhere. I notice it by the fact that the events stop triggering, and the code that they should be executing isn't being executed.
The workaround is to create a loop that runs for ever and periodically unregisters all events, then starts the whole thing again. This is not necessary when running the whole thing in C# as a Windows Service. But since I have created the whole code in Powershell, I would like to make it work. Anyone have an idea why IO.FileSystemWatcher might be dying when used in PowerShell?
$FileSystemWatcher = New-Object IO.FileSystemWatcher $strWatchPath, $strNameFilter -Property @{
IncludeSubdirectories = $boolIncludeSubdirectories;
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite, CreationTime'
}
Then registering events:
Register-ObjectEvent $FileSystemWatcher Created -SourceIdentifier FileCreated -Action { ..... }
So this sets up a file system watcher in PowerShell, and I can do stuff based on the events that happen when files are created, changed, and so on. This is all nice, but what happens is that when the script runs long enough, the $FileSystemWatcher stops after some time. Like it is being garbage collected or something (guesswork). When retrieving the $FileSystemWatcher object and the named events, they tell me nothing new. Also there are no errors to be found anywhere. I notice it by the fact that the events stop triggering, and the code that they should be executing isn't being executed.
The workaround is to create a loop that runs for ever and periodically unregisters all events, then starts the whole thing again. This is not necessary when running the whole thing in C# as a Windows Service. But since I have created the whole code in Powershell, I would like to make it work. Anyone have an idea why IO.FileSystemWatcher might be dying when used in PowerShell?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.