寻求帮助
我正在尝试编写一个监视文件夹中任何文件更改的实用程序,并在power shell控制台上打印信息
从下面的问题中找到了很多帮助,感谢OP和帖子中的答案。
Powershell script to run a .bat file when a file is added to a folder
我现在有一个像这样的脚本
$folder = '\\{Networkname}\Partner1\' # Enter the root path you want to monitor.
$filter = '*' # You can enter a wildcard filter here.
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
write-host "test"
}
当我执行上面的脚本时,我遇到了异常
Register-ObjectEvent : Cannot subscribe to event. A subscriber with source identifier 'FileCreated' already exists.
At C:\Users\sysadmin\Desktop\FileWatcher.ps1:6 char:21
+ Register-ObjectEvent <<<< $fsw Created -SourceIdentifier FileCreated -Action {
+ CategoryInfo : InvalidArgument: (System.IO.FileSystemWatcher:FileSystemWatcher) [Register-ObjectEvent],
ArgumentException
+ FullyQualifiedErrorId : SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand
我刚开始使用Powershell,因为我需要一个监视文件夹中文件更改的实用程序,如果上面的代码中有任何错误,请告诉我,我只是想在控制台上打印更改的文件信息。 / p>
非常感谢任何帮助
感谢。
答案 0 :(得分:0)
有几个问题:
Get-EventSubscriber
查看同一个注册事件
PowerShell会话。FileCreated
&#39; Register-ObjectEvent
cmdlet中的事件
到-EventName
参数。 -Source-Identifier
参数用作一种名称参数。
答案 1 :(得分:0)
如果要重新运行相同的脚本,请在Register-ObjectEvent条目之前添加以下行:
Unregister-Event FileCreated -ErrorAction:SilentlyContinue