Automated Data Protection: PowerShell Backup and Restore Script

An essential guide for IT professionals to automate the backup and restoration of critical files and systems using PowerShell.

In this Guide:

Introduction

Data loss is a disaster for any organization, whether it’s hardware failure, cyberattack or human error. Backing up is not just a best practice – it’s a necessity. This guide provides a PowerShell backup and restore script that automates the process of protecting your data. For IT pros and system administrators, this is a simple way to ensure data integrity, streamline disaster recovery and automate a task that’s often manual and time consuming.

Background

Many organizations use manual processes or expensive software to back up their data. But for everyday tasks like backing up a user’s folder, an application’s data files or a small server’s state, a lightweight, customizable script is often the answer. Data loss is always a risk and having an automated data backup method is key to business continuity. This script fills the need for a simple yet robust solution that can be customized, scheduled and integrated into your existing IT workflows, a core component of your PowerShell disaster recovery plan.

Script

Here is the complete script, both backup and restore functions. Save this as a .ps1 file.

Automated-BackupAndRestore.ps1
Copy to clipboard
# -----------------------------------------------------------------------------
# Script Name: Automated-BackupAndRestore.ps1
# Description: Automates the backup and restoration of specified files and folders.
# -----------------------------------------------------------------------------

# PARAMETERS:
# -SourcePath: The path to the folder or file you want to back up.
# -DestinationPath: The path where the backup will be stored.
# -Restore: A switch to enable the restore function instead of backup.

param(
    [Parameter(Mandatory=$true)]
    [string]$SourcePath,

    [Parameter(Mandatory=$true)]
    [string]$DestinationPath,

    [switch]$Restore
)

# --- SCRIPT LOGIC ---
$logFile = "C:\BackupAndRestore_$(Get-Date -Format 'yyyyMMdd').log"

function Write-Log {
    param($message)
    Add-Content -Path $logFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $message"
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] $message"
}

# --- BACKUP FUNCTION ---
function Start-Backup {
    Write-Log "Starting backup of '$SourcePath' to '$DestinationPath'..."
    
    # Check if the source path exists
    if (-not (Test-Path $SourcePath)) {
        Write-Log "Error: Source path '$SourcePath' not found. Aborting backup." -ForegroundColor Red
        return
    }
    
    # Create a timestamped backup directory
    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $backupDir = Join-Path -Path $DestinationPath -ChildPath "Backup_$timestamp"
    
    # Use Robocopy for a robust and reliable backup
    try {
        Robocopy $SourcePath $backupDir /E /COPYALL /LOG+:$logFile /R:1 /W:1 /MT:16 /V
        Write-Log "Backup completed successfully to '$backupDir'." -ForegroundColor Green
    } catch {
        Write-Log "Backup failed: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# --- RESTORE FUNCTION ---
function Start-Restore {
    Write-Log "Starting restore from '$SourcePath' to '$DestinationPath'..."
    
    # Check if the source (backup) path exists
    if (-not (Test-Path $SourcePath)) {
        Write-Log "Error: Backup source path '$SourcePath' not found. Aborting restore." -ForegroundColor Red
        return
    }

    # Use Robocopy to restore the data
    try {
        Robocopy $SourcePath $DestinationPath /E /COPYALL /LOG+:$logFile /R:1 /W:1 /MT:16 /V
        Write-Log "Restore completed successfully to '$DestinationPath'." -ForegroundColor Green
    } catch {
        Write-Log "Restore failed: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# --- SCRIPT EXECUTION ---
if ($Restore) {
    Start-Restore
} else {
    Start-Backup
}

Detailed Breakdown

FeatureDescription
Backup Function (Start-Backup)This function handles the core backup process. It first validates that the source path exists, then creates a timestamped folder within the destination path.
This versioning feature ensures that each run maintains its own backup, allowing restoration to a specific point in time.
The script uses Robocopy, a reliable built-in Windows utility, to perform the copy.
Robocopy is more robust than Copy-Item for large-scale operations, as it supports long file paths and can recover from network interruptions.
A full list of parameters is available on
Microsoft Learn.
Restore Function (Start-Restore)Triggered by the -Restore switch, this function mirrors the backup logic but reverses the source and destination paths.
This ensures that data from the backup location is accurately copied back to the original or a new location.
Execution LogicThe script’s final lines use a simple if/else statement to determine the execution flow.
If the user passes the -Restore switch, it runs Start-Restore; otherwise, it executes Start-Backup.
This dual-function design makes the script versatile, serving as both a backup and restore solution within one file.

Use Cases

  • Daily Server Backups: Run this script daily using Windows Task Scheduler to backup critical data on your servers, such as application logs, config files and key documents.

  • User Profile Backups: Deploy this script as a login or logoff script to backup a user’s My Documents folder to a central network share so important files are protected.

  • Application Snapshots: Before doing a major application update or making a database change, use this script to backup the application’s data directory. This gives you an instant PowerShell disaster recovery option.

Conclusion

This file backup script is a simple but powerful tool to get you started with your data protection strategy. It won’t replace a full blown enterprise backup solution but is perfect for automating daily backups of specific files and folders. It’s flexible and easy to use so it’s a must have for any IT pro. This script is a key part of any disaster recovery plan so you can quickly and easily recover from data loss incidents. For more information on automating scripts please see our guide on Scheduling PowerShell Scripts with Task Scheduler.

Deploy this script across your Endpoints with Zecurit

Upload this script to Zecurit's Script Repository and execute it across hundreds of endpoints in minutes. Support for PowerShell, Bash, Python,and more with full audit trails and scheduling.

Frequently Asked Questions (FAQs)

  • How do I schedule this script to run automatically?

    You can use Windows Task Scheduler. Simply create a new task, set a trigger (e.g., daily at 2:00 AM), and configure the action to run PowerShell.exe with the script path and parameters as arguments.

  • What permissions are required for the script to work?

    The user account running the script must have read access to the $SourcePath and write access to the $DestinationPath. For network locations, the account needs to have permissions on the network share.

  • Does this script handle versioning?

    Yes, the script automatically handles versioning by creating a new timestamped folder for each backup run. This allows you to retain multiple backups and restore to a specific point in time, protecting you from data corruption or accidental deletions that might go unnoticed for a few days.

  • How do I restore a specific backup?

    To restore, you must provide the exact path to the timestamped backup folder as the -SourcePath parameter. For example: .\Automated-BackupAndRestore.ps1 -SourcePath "C:\Backups\Backup_20250910_100000" -DestinationPath "C:\OriginalData" -Restore.