Synchronizing Directories in Windows Server Using PowerShell and Task Scheduler

1 year ago

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

  • Press Win + R, type taskschd.msc, and press Enter.


Create a New Task

  • Click on Create Task in the right-hand Actions pane.


General Tab

  • Name your task, e.g., Directory Sync.
  • Set the task to run whether the user is logged on or not.
  • Select Run with highest privileges.


Triggers Tab:

  • Click New... to create a new trigger.
  • Set it to begin the task At startup.
  • Optionally, you can add additional triggers as needed.


Actions Tab

  • Click New… to create a new action.
  • Set the action to Start a program.
  • In the Program/script box, enter powershell.exe
  • In the Add arguments (optional) box, enter -File "D:\Script\ContinuousSync.ps1".


(Replace D:\Script\ContinuousSync.ps1 with the actual path to your PowerShell script.)

Conditions Tab

  • Adjust conditions to suit your needs (e.g., you might want to uncheck Start the task only if the computer is on AC power).

Settings Tab

  • Ensure Allow task to be run on demand is checked.
  • Set If the task fails, restart every to 1 minute and Attempt to restart up to to 3 times.

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
Please Login to Post a Comment