Skip to content

Instantly share code, notes, and snippets.

@WillPresley
Last active March 22, 2024 16:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save WillPresley/e662e07fa966de41de7e045b2bf05ff7 to your computer and use it in GitHub Desktop.
Save WillPresley/e662e07fa966de41de7e045b2bf05ff7 to your computer and use it in GitHub Desktop.
Backup WSL2 Virtual Disks and Compress with 7-Zip
# Backup WSL2 virtual disks using native functions and compress them using 7zip
## Will Presley, 2020
## willpresley.com
#### http://mats.gardstad.se/matscodemix/2009/02/05/calling-7-zip-from-powershell/
# Alias for 7-zip
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
#### Alternative native PS 7-zip: https://www.sans.org/blog/powershell-7-zip-module-versus-compress-archive-with-encryption/
################### Variables ###################
$wslDistName = "{{ENTER_NAME_FROM_WSL_LIST_HERE}}"
$currentDate = (Get-Date).ToString('yyyy-MM-dd')
$backupDirectory = "X:\{{ENTER_DIRECTORY_STRUCTURE_HERE}}"
$backupName = "{{ENTER_BACKUP_FILENAME_HERE}}"
$backupsToKeep = 6
$filePath = -join("$backupDirectory", "\", "$backupName", "_", "$currentDate", ".tar")
################ End of Variables ###############
## Run the export to get the .tar file
wsl --export "$wslDistName" "$filePath"
## Let's compress it using 7zip and max compression, and use -sdel to delete the original file after successful compression
sz a -t7z -mx=9 -sdel "$filePath.7z" "$filePath"
## Let's remove everything except the last X backups (X month history)
gci "$backupDirectory" -Recurse| where{-not $_.PsIsContainer} | sort LastWriteTime -desc | select -Skip $backupsToKeep | Remove-Item -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment