Using PowerShell and UnRAR for Daily Backup Extraction
Automating backup restoration is critical for verifying data integrity and maintaining updated secondary environments. This guide explains how to build a PowerShell script that uses the command-line utility UnRAR to automatically locate and extract daily RAR backup archives, complete with error logging and automated scheduling instructions using Windows Task Scheduler.
Prerequisites
To implement this workflow, ensure the following requirements are met:
- UnRAR Utility: Download
UnRAR.exe(part of the WinRAR package or the standalone command-line version) and place it in a known directory, such asC:\Program Files\WinRAR\UnRAR.exe. - Execution Rights: Ensure your PowerShell execution
policy allows running custom scripts (
RemoteSignedorBypass).
PowerShell Script Implementation
The script below identifies the most recent backup archive matching a
specific pattern, checks if the destination directory exists, and
invokes UnRAR.exe to perform the extraction.
# Configuration paths
$UnrarPath = "C:\Program Files\WinRAR\UnRAR.exe"
$BackupDir = "D:\Backups\Daily"
$ExtractDir = "E:\Restores\Today"
$LogFile = "C:\Logs\BackupExtraction.log"
# Function to write log messages
function Write-Log {
param ([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $LogFile -Value "[$Timestamp] $Message"
}
# Ensure destination directory exists
if (-not (Test-Path -Path $ExtractDir)) {
New-Item -ItemType Directory -Path $ExtractDir -Force | Out-Null
Write-Log "Created extraction directory: $ExtractDir"
}
# Locate the newest RAR file modified in the last 24 hours
$LatestArchive = Get-ChildItem -Path $BackupDir -Filter "*.rar" |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if ($LatestArchive) {
Write-Log "Found backup file: $($LatestArchive.FullName)"
# UnRAR parameters:
# x = Extract files with full path
# -o+ = Overwrite existing files
# -y = Assume Yes on all queries
$UnrarArgs = @("x", "-o+", "-y", "`"$($LatestArchive.FullName)`"", "`"$ExtractDir\`"")
try {
Write-Log "Starting extraction..."
$Process = Start-Process -FilePath $UnrarPath -ArgumentList $UnrarArgs -Wait -NoNewWindow -PassThru
if ($Process.ExitCode -eq 0) {
Write-Log "Extraction completed successfully."
} else {
Write-Log "UnRAR failed with exit code: $($Process.ExitCode)"
}
}
catch {
Write-Log "Error executing extraction: $_"
}
} else {
Write-Log "Warning: No backup archive found in $BackupDir."
}Explanation of Key UnRAR Switches
x: Extracts files while preserving the original folder structure stored inside the archive.-o+: Automatically overwrites any existing files in the destination directory to ensure stale data is replaced.-y: Suppresses all user prompts by answering "Yes" by default, preventing the script from hanging during unattended execution.
Automating the Script Daily
To run the extraction automatically, schedule it via Windows Task Scheduler:
- Open Task Scheduler and select Create Basic Task.
- Name the task (e.g.,
Daily-Backup-Extraction) and set the trigger to Daily at your preferred time. - For the action, select Start a program.
- In the Program/script field, enter:
powershell.exe - In the Add arguments (optional) field, provide the
execution parameters:
-ExecutionPolicy Bypass -File "C:\Scripts\ExtractBackup.ps1" - Finish the setup and ensure the task is configured to "Run whether user is logged on or not" with administrative privileges.