We help IT Professionals succeed at work.

Two-Way Folder Sync Using Powershell

Ray Turner
Ray Turner asked
on
Is there a way to create a Powershell script that will perform a two-way folder sync?  I tried Robocopy and could not get it to work.
Comment
Watch Question

Paul MacDonaldDirector, Information Systems

Commented:
How did Robocopy fail?
Is there a way to create a Powershell script that will perform a two-way folder sync?  I tried Robocopy and could not get it to work.

I agree with Paul, this is Robocopy's bread and butter. If you're having trouble with it refer to this excellent guide.

https://adamtheautomator.com/robocopy-the-ultimate/
Jose Gabriel Ortega CastroCEO Faru Bonon IT /Top Rated Freelancer on Upwork / Photographer
Awarded 2018
Distinguished Expert 2018

Commented:

Hello I'd created a script on powershell to do this:
https://gallery.technet.microsoft.com/scriptcenter/Copy-Files-from-folderA-to-29710ef9

This creates copies of fiels and folders  oneway and preserves permissions.

Ray TurnerSenior Consultant

Author

Commented:
Here's what I have.  Is this correct?

function Sync($sourceFolder, $targetFolder, $filter) {
    ROBOCOPY $sourceFolder $targetFolder $filter /XO /E /S /FFT /Z /XA:H /W:2 /R:5 /NP /NJH /NJS /NDL /NC /NS

    ROBOCOPY $targetFolder $sourceFolder $filter /XO /E /S /FFT /Z /XA:H /W:2 /R:5 /NP /NJH /NJS /NDL /NC /NS
}
Ray TurnerSenior Consultant

Author

Commented:
I have my Workstation at home and a Laptop I take on the road.  I'm using a USB Drive & Powershell to keep the two computers in sync.
Director, Information Systems
Commented:
This...

    ROBOCOPY $sourceFolder $targetFolder /MIR

...is a Robocopy sync, and will copy all the files from source to target that don't already exist.  It will also delete any files in target that don't exist in the source.  You could reverse it as necessary...

    ROBOCOPY $targetFolder $sourceFolder /MIR


I'm guessing you want to keep the most recent version of any file, and copy any files that don't already exist.  I'm also guessing this is a script you're firing off manually or on a schedule and not running constantly.  You're close with your script.  I'd try...

    function Sync($sourceFolder, $targetFolder, $filter) {
        ROBOCOPY $sourceFolder $targetFolder $filter /XO /E /Z /XA:H /R:5 /NP /NJH /NJS /NDL /NC /NS

        ROBOCOPY $targetFolder $sourceFolder $filter /XO /E /Z /XA:H /R:5 /NP /NJH /NJS /NDL /NC /NS
    }


...and see if that works better.  If not, let us know what it does and doesn't do that you need done.
Are you getting an error message?  What message are you getting?
Ray TurnerSenior Consultant

Author

Commented:
Thanks!