Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep 2 folders in sync using powershell script

Tags:

powershell

We have two folders:

  • FolderA: D:\Powershell\Original
  • FolderB: D:\Powershell\copy

Now, I want to keep FolderA and FolderB in sync (i.e. when a user changes/adds/removes a file/directory in FolderA then same changes should happen in FolderB).

I tried :

$Date = Get-Date  $Date2Str = $Date.ToString("yyyMMdd")  $Files = gci "D:\Powershell\Original"  ForEach ($File in $Files){         $FileDate = $File.LastWriteTime         $CTDate2Str = $FileDate.ToString("yyyyMMdd")         if ($CTDate2Str -eq $Date2Str) {             copy-item "D:\Powershell\Original" "D:\Powershell\copy" -recurse                -ErrorVariable capturedErrors -ErrorAction SilentlyContinue;          }  } 

But this would require a similar powershell script for deletion of files in FolderA and changes in FolderB.

like image 344
Sunil Kumar Avatar asked Sep 16 '14 13:09

Sunil Kumar


People also ask

Can I sync two folders?

You have three different sync options; Synchronize, Echo, and Contribute. When you select each of these options, you will see a description telling you how each sync works. Synchronization will sync all files and folders between two folders.

How do I sync folders locally?

To sync a share locally, open its preferences or right-click on it in Sync and select "Sync local folders". Choose the access permissions for the local share, path and enable, if necessary, Selective Sync. USB and network paths are supported.


1 Answers

Have you looked at Robocopy (Robust File Copy)? It can be used with PS and provides what your looking for i.e. it is designed for reliable copying or mirroring of folders (changes/adds/removes) just select the options as required.

Robocopy sourceFolder destinationFolder /MIR /FFT /Z /XA:H /W:5

The /MIR option mirrors the source directory and the destination directory. It will delete files at the destination if they were deleted at the source.

Robocopy

like image 57
clD Avatar answered Oct 09 '22 09:10

clD