Power Shell脚本监视文件夹以更改文件并在控制台上打印信息

问题描述 投票:0回答:2

寻求帮助

我正在尝试编写一个实用程序来监视文件夹中的任何文件更改并在电源外壳控制台上打印信息

从下面的问题找到了很多帮助,感谢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,因为我需要一个监视文件夹中文件更改的实用程序,如果上面的代码中有任何错误,请告诉我,我只是想在控制台上打印更改的文件信息。

任何帮助都非常感谢

谢谢。

powershell file-watcher
2个回答
0
投票

有几个问题:

  1. 您已在同一会话中运行该脚本两次,因此已存在具有相同名称的事件监视器。使用Get-EventSubscriber查看同一PowerShell会话中的已注册事件。
  2. 您需要将FileCreated cmdlet中的'Register-ObjectEvent'事件移动到-EventName参数。

-Source-Identifier参数用作一种名称参数。


0
投票

如果要重新运行相同的脚本,请在Register-ObjectEvent条目之前添加以下行:

Unregister-Event FileCreated -ErrorAction:SilentlyContinue
© www.soinside.com 2019 - 2024. All rights reserved.