Search This Blog

Sunday, March 10, 2024

PowerShell: File backup script

This simple script allows you to backup a chosen folder to a set destination.

This script contains the main engine so to speak, but you can build further using this as a base. Some suggestions might be to add failsafe features or a GUI.

You can also add options to delete/manage existing backups as they exists as simple .zip-files.
Another option you might want to look into is how to revert to an older backup.

I used this script for backing up my Minecraft world, on my MC server. Basically I customized the base script to stop the bedrock_server service as well, as it was blocking the compression. Then it saved the world as a .zip file on a separate disk. This script checks if there was a backup already made today, but of course you can change this to perhaps create a more granular filename to avoid collisions 

Param(

  [string]$Path = 'C:\Temp\App',

  [string]$DestinationPath = 'D:\Backup\'

)

If (-Not (Test-Path $Path)) 

{

  Throw "The source directory $Path does not exist, please specify an existing directory"

}

$date = Get-Date -format "yyyy-MM-dd"

$DestinationFile = "$($DestinationPath + 'backup-' + $date + '.zip')"

If (-Not (Test-Path $DestinationFile)) 

{

  Compress-Archive -Path $Path -CompressionLevel 'Fastest' -DestinationPath "$($DestinationPath + 'backup-' + $date)"

  Write-Host "Created backup at $($DestinationPath + 'backup-' + $date + '.zip')"

} Else {

  Write-Error "Today's backup already exists"

}

No comments:

Post a Comment