取消注册已注册的FileWatcher事件不起作用 [英] Unregister a registered filewatcher event does not work

查看:151
本文介绍了取消注册已注册的FileWatcher事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想观看带有powershell的文件夹,我是PS初学者.

I want to watch a folder with powershell and I am a PS beginner.

启动脚本后,该脚本可以运行一次.

That script works ONE time when I start the script.

但是当我由于更改了一些脚本代码而不得不再次重新启动脚本时,会收到以下错误消息:

But when I have to restart the script again because I changed some script code I get this error message:

Cannot subscribe to the specified event. A subscriber with the source identifier 'FileChanged' already exists.

我尝试过:

此代码位于脚本顶部:

Unregister-Event -SourceIdentifier FileChanged

不起作用.

如何正确取消注册该事件,以便我可以根据需要多次运行脚本并处置先前注册的事件?

How do I correctly unregister the event so I can run my script as often I want and the previously registered event is disposed?

代码

$folder = "C:\temp"

$Watcher = New-Object IO.FileSystemWatcher $folder -Property @{ 
    IncludeSubdirectories = $true
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
} 

$onChanged = Register-ObjectEvent $Watcher Changed -SourceIdentifier FileChanged -Action {
   $path = $Event.SourceEventArgs.FullPath
   $name = $Event.SourceEventArgs.Name
   $changeType = $Event.SourceEventArgs.ChangeType
   $timeStamp = $Event.TimeGenerated
   Write-Host "The file '$name' was $changeType at $timeStamp"
   Write-Host $path
   #Move-Item $path -Destination $destination -Force -Verbose
}

推荐答案

好吧,看看您要达到的目标...要回答您的原始问题,您需要执行以下操作以取消注册该事件.

Ok, looking at what your trying to achieve... to answer your original question, you need to do the following to unregistered the event.

Get-EventSubscriber -SourceIdentifier "filechanged" | Unregister-Event

我必须问你为什么要对代码进行1000次调整.如果您尝试注册1000个要监视的不同事件,则使用++修饰符循环并递增变量会更有意义.

I have to ask why are you having to make 1000 adjustments to the code. If you are trying to register 1000 different events to be monitored it would make more sense to loop and increment a variable using the ++ modifier.

如果这是您要完成的工作,那么我已经实现了这一点,并且可以在需要时共享一些代码.

I have achieved this already if this is what your tying to accomplish and can share some code if you need it.

这篇关于取消注册已注册的FileWatcher事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆