Last active
March 8, 2024 22:06
-
-
Save atbore-phx/69ab43e8b48db412211f29b9b186eeca to your computer and use it in GitHub Desktop.
backup, encrypt (7z), and rotate your wsl distribution via powershell script
This file contains 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
# Requirements: | |
## install google drive for desktop | |
## Install 7z.exe | |
## 7z.exe must be in your Path env variable | |
# Define your parameters | |
$wslDist = "<your_wsl_name>" # WSL Distribution | |
$tempDirectory = [System.IO.Path]::GetTempPath() | |
$backupFolder = "G:\My Drive\backup\Wsl\$($wslDist)" # Backup destination | |
$date = Get-Date -Format "yyyyMMddHHmm" | |
$tarFile = "$($wslDist)_backup_$($date).tar" | |
$backupFile = Join-Path -Path $tempDirectory -ChildPath $tarFile | |
$zipFile = Join-Path -Path $backupFolder -ChildPath "$($tarFile).7z" | |
$zipPassword = "<your_password>" # Set your password | |
$maxBackups = 5 # Maximum number of backups to keep | |
# Ensure the backup folder exists | |
if (!(Test-Path -Path $backupFolder -PathType Container)) { | |
New-Item -Path $backupFolder -ItemType Directory | Out-Null | |
} | |
# Export the WSL Distribution | |
wsl --export $wslDist $backupFile | |
# Ensure 7zip is installed and in PATH, then compress with 7zip and password protect | |
if ((Get-Command "7z.exe" -ErrorAction SilentlyContinue) -ne $null) { | |
7z.exe a -t7z -mx=1 -p"$zipPassword" $zipFile $backupFile | |
Remove-Item -Path $backupFile | |
} else { | |
Write-Host "7zip is not installed or not in PATH. The backup couldn't be compressed and password protected." | |
} | |
# Get all backup files | |
$backupFiles = Get-ChildItem -Path $backupFolder -Filter "*.7z" | Sort-Object -Property CreationTime | |
# Delete oldest backups if exceeding maxBackups | |
while ($backupFiles.Count -gt $maxBackups) { | |
Remove-Item -Path $backupFiles[0].FullName -Force | |
$backupFiles = Get-ChildItem -Path $backupFolder -Filter "*.7z" | Sort-Object -Property CreationTime | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment