← script library

Efficient File Backup Script in PowerShell

Backup & RecoveryJanuary 12, 2025

This PowerShell script efficiently backs up files from a specified source directory to a designated backup directory. It provides error handling and logging for a seamless experience.

powershell
$sourceDir = "C:\Path\To\Source"
$backupDir = "D:\Path\To\Backup"

if (-not (Test-Path $backupDir)) {
    New-Item -ItemType Directory -Path $backupDir
}

$filesToBackup = Get-ChildItem -Path $sourceDir -File

foreach ($file in $filesToBackup) {
    try {
        Copy-Item -Path $file.FullName -Destination $backupDir -ErrorAction Stop
        Write-Host "Successfully backed up $($file.Name)"
    } catch {
        Write-Host "Failed to backup $($file.Name): $_"
    }
}

$backupCount = $filesToBackup.Count
Write-Host "$backupCount files have been backed up to $backupDir."

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.