Last active
April 17, 2025 04:33
-
-
Save WillPresley/e662e07fa966de41de7e045b2bf05ff7 to your computer and use it in GitHub Desktop.
Backup WSL2 Virtual Disks and Compress with 7-Zip
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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