Preserving Folder Structure When Copying Files Monitored with IO.FileSystemWatcher RRS feed

  • Question

  • Hey Guys - 

    I'm writing a script which among other things monitors a specific share (including sub-folders) and when a change of any file is detected, it should copy the change to a 2nd share.  The issue I'm having during testing is when a change is detected of a file within a subfolder, it copies the changed file to the root of the target share - not the same folder it resided in on the source.

    Below is an example followed by my code.  I'm sure it's something like a simple parameter I'm leaving out, but been staring at it too long :)


    • Monitored Share: \\server1\files\
    • Target Share: \\server2\files\

    With script running - if the file test.txt changes (or is added) within \\server1\files\folder\, the changed file is copied into \\server2\files\ - not \\server2\files\folder\

    Current Script

    $sourceshare = "\\server1\files"

    $targetshare = "\\server2\files"

    $filter = '*.*'

    $fsw = New-Object IO.FileSystemWatcher $sourceshare, $filter -Property @{
     IncludeSubdirectories = $true
     NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
    $onCreated = Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
     $path = $Event.SourceEventArgs.FullPath
     $name = $Event.SourceEventArgs.Name
     $changeType = $Event.SourceEventArgs.ChangeType
     $timeStamp = $Event.TimeGenerated
     Copy-Item $path -Destination $targetshare -Force -Verbose

    Any suggestions?  Thanks!

    Ben K.

    Monday, November 18, 2019 9:42 PM

All replies

  • Copy-Item $path -Destination \\server2\files


    Monday, November 18, 2019 9:48 PM
  • Best method:

    $onCreated = Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
      Copy-Item $Event.SourceEventArgs.FullPath -Destination \\server2\files


    Monday, November 18, 2019 9:50 PM
  • Hi,

    Was your issue resolved?

    If you resolved it using our solution, please "mark it as answer" to help other community members find the helpful reply quickly.

    If you resolve it using your own solution, please share your experience and solution here. It will be very beneficial for other community members who have similar questions.

    If no, please reply and tell us the current situation in order to provide further help.

    Best Regards,


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact

    Friday, December 6, 2019 7:24 AM