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



寻求帮助

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

从下面的问题中找到了很多帮助,感谢 OP 和线程中的答案。

Powershell 脚本,用于在将文件添加到文件夹时运行.bat文件

我现在有一个这样的脚本

$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:UserssysadminDesktopFileWatcher.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,因为我需要一个实用程序来监视文件夹中的文件更改,如果上面的代码中有任何错误,请告诉我,我只是尝试在控制台上打印更改的文件信息。

任何帮助都非常感谢

谢谢。

如果要

重新运行同一脚本,请在 Register-ObjectEvent 条目之前添加以下行:

Unregister-Event FileCreated -ErrorAction:SilentlyContinue

有几个问题:

  1. 您在同一会话中运行了两次脚本,因此事件观察程序已存在,具有相同的名称。 用 Get-EventSubscriber查看同一事件中的已注册事件PowerShell 会话。
  2. 您需要在Register-ObjectEvent cmdlet 中移动"FileCreated"事件到-EventName参数。

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

最新更新