Folder Synchronization Script

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.
If you are interested in efficient server management solutions, check out our software, ServerEngine, at https://serverengine.co. Let’s explore the script step by step.
### Step 1: Define Source and Target Directories
The first step is to define the source and target directories that you want to synchronize. The source directory contains the files you want to sync, and the target directory is where the files should be copied to.

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

### Step 2: Check and Create Target Directory
Before synchronizing, its good practice to check if the target directory exists. If it doesn’t, the script will create it to ensure that we have a place to store the synchronized files.

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

### Step 3: Synchronize Files
In this step, we will get all files from the source directory and copy them to the target directory if they dont exist there or if they are newer in the source directory.

$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"
    }
}

### Step 4: Summary of Synchronization
Finally, the script provides a summary of the synchronization process, letting you know that the operation has been completed and listing the files that were copied.

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

Feel free to customize the directory paths to match your requirements. This script is handy for maintaining backups or mirroring directories! Stay tuned for more useful PowerShell scripts on our website!