← script library

Folder Synchronization Script

Files & FoldersJanuary 11, 2025

In this post, we provide a PowerShell script that syncs the contents of two folders. This script is useful for keeping backups up-to-date or ensuring two directories maintain the same files.

powershell
$sourceDirectory = 'C:\SourceFolder'
$targetDirectory = 'D:\TargetFolder'

if (-Not (Test-Path -Path $targetDirectory)) {
    New-Item -ItemType Directory -Path $targetDirectory
    Write-Host "Created directory: $targetDirectory"
}

$files = Get-ChildItem -Path $sourceDirectory -File
foreach ($file in $files) {
    $targetFilePath = Join-Path -Path $targetDirectory -ChildPath $file.Name
    if (-Not (Test-Path -Path $targetFilePath) -or ($file.LastWriteTime -gt (Get-Item $targetFilePath).LastWriteTime)) {
        Copy-Item -Path $file.FullName -Destination $targetDirectory -Force
        Write-Host "Synced: $($file.Name) to $targetDirectory"
    }
}

Write-Host "Folder synchronization completed. Files from '$sourceDirectory' have been synced to '$targetDirectory'."

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.