Question:
I am new to PowerShell and I am trying to use the System.IO.FileSystemWatcher to monitor the presence of a file in a specified folder. However, as soon as the file is detected I want to stop monitoring this folder immediately and stop the FileSystemWatcher. The plan is to incorporate the PowerShell script into a SQL Agent to enable users to restore their own databases. Basically I need to know the command to stop FileSystemWatcher from monitoring as soon as one file is found. Here is the script so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = "C:\TriggerBatch" $watcher.Filter = "*.*" $watcher.IncludeSubdirectories = $true $watcher.EnableRaisingEvents = $true ### DEFINE ACTIONS AFTER A EVENT IS DETECTED $action = { $path = $Event.SourceEventArgs.FullPath $changeType = $Event.SourceEventArgs.ChangeType $logline = "$(Get-Date), $changeType, $path" Add-content "C:\log2.txt" -value $logline } ### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY $created = Register-ObjectEvent $watcher Created -Action $action while ($true) {sleep 1} ## Unregister-Event Created ?? ##Stop-ScheduledTask ?? |
Answer:
1 2 |
Unregister-Event $created.Id |
This will unregister the event. You will probably want to add this to the $action.
Do note that if there are events in the queue they will still be fired.
This might help too.