Maintaining synchronized directories is a common necessity in a Windows Server environment, particularly when you need a backup or when several computers need to access the same data. This blog post will walk you through configuring Task Scheduler and PowerShell to automatically synchronize two directories.
Scenario
You have two directories:
Source: Z:\
Destination: D:\Data\backup\
The goal is to keep the destination directory up to date with the source directory at all times. First create a PowerShell Script. Windows PowerShell is a powerful scripting language that can automate a variety of tasks. We’ll use Robocopy (Robust File Copy) within a PowerShell script to handle the synchronization.
Open a Text Editor: Open Notepad or any other text editor and write a following scripts
$source = "Z:\"
$destination = "E:\Data\backup\"
while ($true) {
Robocopy $source $destination /MIR /FFT /Z /XA:H /W:10 /R:5
if ($LASTEXITCODE -gt 7) {
Write-Error "Robocopy failed with exit code $LASTEXITCODE"
}
Start-Sleep -Seconds 60
}
Now, Save the file with a .ps1 extension, for example, SyncDirectories.ps1.
Create a Scheduled Task to Run the Script at Startup
Start Task Schedular
Create a New Task
General Tab
Triggers Tab:
Actions Tab
(Replace D:\Script\ContinuousSync.ps1 with the actual path to your PowerShell script.)
Conditions Tab
Settings Tab
By following these steps, you will have a setup that keeps the directories in sync every 1 minute, running in the background without showing any command-line windows to the user.
785