监视和复制到和从多个位置

Monitor and copy to and from multiple locations

尝试使用具有两个网卡的桥接 PC 自动将文件从一台 PC(不在网络上)复制到网络位置。

我已经设法将之前关于该主题的 post 中的脚本拼凑在一起。这很好用!

我遇到的问题是我需要监视文件并将其从 PC 上的两个位置复制到桥接 PC 上的两个不同位置

C:\Source → C:\Destination

C:\Source2 → C:\Destination2

我尝试了 运行ning 2 个具有不同源和目标的 PowerShell 脚本,但是它不允许第二个 运行 而第一个 运行ning。出现以下错误消息:

Register-ObjectEvent : Cannot subscribe to the specified event. A subscriber
with the source identifier 'FileCreated' already exists.
At ****\PowerShell\movePowerhell - Copy.ps1:8 char:14
+ ... onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileC ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (System.IO.FileSystemWatcher:FileSystemWatcher) [Register-ObjectEvent], ArgumentException
    + FullyQualifiedErrorId : SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand

我假设我需要在同一个脚本中监控两个位置并复制到两个目的地?

我已经尝试创建一个包含源和目标的数组并循环遍历代码两次,但我得到与上述相同的错误。

$folder = "C:\Source"
$filter = "*.*"
requirements
$destination = "C:\Destination"
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
    IncludeSubdirectories = $true
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $path = $Event.SourceEventArgs.FullPath
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated

    Move-Item $path -Destination $destination -Force -Verbose # Force will overwrite files with same name
}

如有疑问,请阅读 documentation(强调我的):

-SourceIdentifier

Specifies a name that you select for the subscription. The name that you select must be unique in the current session. The default value is the GUID that Windows PowerShell assigns.

避免此问题的最简单方法是不指定源标识符。如果省略该参数,PowerShell 将自动设置一个 GUID 作为源标识符,这将避免名称冲突。