Skip to content

Instantly share code, notes, and snippets.

@mohatb
Last active January 31, 2023 08:31
Show Gist options
  • Select an option

  • Save mohatb/56d70e3850c19a72cbe4bce5aaf92021 to your computer and use it in GitHub Desktop.

Select an option

Save mohatb/56d70e3850c19a72cbe4bce5aaf92021 to your computer and use it in GitHub Desktop.
Backup-restore WSL Powershell
# Backup WSL
# Backup WSL
#.\script.ps1 backup 'C:\wsl-backup'
# Restore WSL
#.\script.ps1 restore 'C:\wsl-backup'
function Backup-WSL {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$BackupDirectory
)
# Create backup directory if it doesn't exist
if (!(Test-Path $BackupDirectory)) {
New-Item -ItemType Directory -Path $BackupDirectory | Out-Null
}
# Get list of WSL distros
$distros = wsl --list --quiet
# Backup each distro
foreach ($distro in $distros) {
wsl --export $distro "$BackupDirectory\$distro.tar"
}
}
# Restore WSL
function Restore-WSL {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$BackupDirectory
)
# Get list of backup files
$backupFiles = Get-ChildItem $BackupDirectory
# Restore each backup file
foreach ($backupFile in $backupFiles) {
$distro = $backupFile.BaseName -replace '.tar',''
wsl --import $distro "$BackupDirectory\$backupFile"
}
}
# Main function
function Main {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$Command,
[Parameter(Mandatory=$true)]
[string]$BackupDirectory
)
if ($Command -eq 'backup') {
Backup-WSL -BackupDirectory $BackupDirectory
}
elseif ($Command -eq 'restore') {
Restore-WSL -BackupDirectory $BackupDirectory
}
else {
Write-Error 'Error: Invalid command'
return 1
}
}
Main -Command $args[0] -BackupDirectory $args[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment