用于监视文件夹以更改文件的Power Shell脚本并在控制台

时间:2017-06-09 15:41:59

标签: powershell file-watcher

寻求帮助

我正在尝试编写一个监视文件夹中任何文件更改的实用程序,并在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>

非常感谢任何帮助

感谢。

2 个答案:

答案 0 :(得分:0)

有几个问题:

  1. 你在同一个会话中运行了两次这样的脚本 event-watcher已经存在,名称相同。使用 Get-EventSubscriber查看同一个注册事件 PowerShell会话。
  2. 您需要移动&#39; FileCreated&#39; Register-ObjectEvent cmdlet中的事件 到-EventName参数。
  3. -Source-Identifier参数用作一种名称参数。

答案 1 :(得分:0)

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

Unregister-Event FileCreated -ErrorAction:SilentlyContinue