PowerShell Script to Backup Files Easily
Copy-Item -Path 'source_path\*' -Destination 'backup_path' -Recurse -Force in PowerShell to backup files from one folder to another, copying all files and subfolders.Examples
How to Think About It
Algorithm
Code
param(
[string]$Source = "C:\Data",
[string]$Destination = "D:\Backup"
)
if (-not (Test-Path -Path $Destination)) {
New-Item -ItemType Directory -Path $Destination | Out-Null
}
Copy-Item -Path "$Source\*" -Destination $Destination -Recurse -Force
Write-Output "Backup completed from $Source to $Destination"Dry Run
Let's trace backing up files from C:\Data to D:\Backup through the code
Check if destination exists
Destination D:\Backup does not exist, so create it.
Copy files recursively
Copy all files and folders from C:\Data to D:\Backup, overwriting if needed.
Print confirmation
Output message: Backup completed from C:\Data to D:\Backup
| Step | Action | Value |
|---|---|---|
| 1 | Check destination folder | D:\Backup (not found, created) |
| 2 | Copy files | From C:\Data to D:\Backup recursively |
| 3 | Print output | Backup completed from C:\Data to D:\Backup |
Why This Works
Step 1: Create destination folder if missing
The script uses Test-Path to check if the backup folder exists and New-Item to create it if not, ensuring the backup has a place to go.
Step 2: Copy files recursively
Using Copy-Item with -Recurse copies all files and subfolders from source to destination, preserving folder structure.
Step 3: Overwrite existing files
The -Force flag makes sure existing files in the destination are overwritten, keeping the backup up to date.
Step 4: Confirm backup completion
The script prints a message with Write-Output to let the user know the backup finished successfully.
Alternative Approaches
param(
[string]$Source = "C:\Data",
[string]$Destination = "D:\Backup"
)
robocopy $Source $Destination /MIR /Z /NP
Write-Output "Backup completed using RoboCopy from $Source to $Destination"param(
[string]$Source = "C:\Data",
[string]$ZipFile = "D:\Backup\DataBackup.zip"
)
if (-not (Test-Path -Path (Split-Path $ZipFile))) {
New-Item -ItemType Directory -Path (Split-Path $ZipFile) | Out-Null
}
Compress-Archive -Path "$Source\*" -DestinationPath $ZipFile -Force
Write-Output "Backup compressed to $ZipFile"Complexity: O(n) time, O(n) space
Time Complexity
The script copies each file and folder once, so time grows linearly with the number of files (n).
Space Complexity
Extra space depends on the size of files copied; the script itself uses minimal memory.
Which Approach is Fastest?
Using RoboCopy is generally faster and more efficient for large backups compared to Copy-Item.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Copy-Item | O(n) | O(n) | Simple backups, small to medium folders |
| RoboCopy | O(n) | O(n) | Large backups, robust copying with resume |
| Compress-Archive | O(n) | O(n) | Space-saving backups, archiving |
-Recurse causes only top-level files to copy, missing subfolders.