Search code examples
powershellfilesystemwatcher

Monitor and copy to and from multiple locations


Trying to automatically copy files from one PC (not on network) to a network location using a bridging PC with two network cards.

I have managed to put together this script from a previous post on the subject. This works great!

The issue I have is that I need to monitor and copy files from two locations on the PC to two separate locations on the bridging PC

C:\Source → C:\Destination

and

C:\Source2 → C:\Destination2

I tried running 2 PowerShell scripts with different sources and destinations however it wont allow the second to run while the first is running. The following error message occurs:

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

I assume I need to monitor both locations and copy to both destinations in the same script?

I have tried creating a array with both sources and destinations and looping through the code twice but I get the same error as above.

$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
}

Solution

  • When in doubt, read the documentation (emphasis mine):

    -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.

    The simplest way to avoid the issue is to not specify a source identifier. If you omit the parameter PowerShell will automatically set a GUID as the source identifier, which will avoid name collisions.