Powershell and System.IO.FileSystemWatcher

帅比萌擦擦* 提交于 2019-11-30 10:09:43
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.

Scriptblocks that are run as an action on a subscribed event have access to the $Args, $Event, $EventArgs and $EventSubscriber automatic variables.

Just add the Unregister-Event command to the end of your scriptblock, like so:

### 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  
            Unregister-Event -SubscriptionId $EventSubscriber.SubscriptionId            
          }    

This is the pattern for an event that only performs an action once and then cleans itself up.

It's difficult to effectively explore these automatic variables since they are within the scope of a Job, but you can futz with them by assigning them to global variables while you are sketching out your code. You may also get some joy with Wait-Debugger and Debug-Runspace. In the case of the $EventSubscriber variable, it returns the exact object you get if you run Get-EventSubscriber (having created a single subscription already). That's how I found the SubscriptionId property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!