Files
MajorWiki/01-linux/distro-specific/wsl2-backup-powershell.md

2.9 KiB
Raw Blame History

title, domain, category, tags, status, created, updated
title domain category tags status created updated
WSL2 Backup via PowerShell Scheduled Task linux distro-specific
wsl2
windows
backup
powershell
majorrig
published 2026-03-16 2026-03-16

WSL2 Backup via PowerShell Scheduled Task

WSL2 distributions are stored as a VHDX file on disk. Unlike traditional VMs, there's no built-in snapshot or backup mechanism. This article covers a simple weekly backup strategy using wsl --export and a PowerShell scheduled task.

The Short Answer

Save this as C:\Users\majli\Scripts\backup-wsl.ps1 and register it as a weekly scheduled task.

Backup Script

$BackupDir = "D:\WSL\Backups"
$Date = Get-Date -Format "yyyy-MM-dd"
$BackupFile = "$BackupDir\FedoraLinux-43-$Date.tar"
$MaxBackups = 3

New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null

# Must shut down WSL first — export fails if VHDX is locked
Write-Host "Shutting down WSL2..."
wsl --shutdown
Start-Sleep -Seconds 5

Write-Host "Backing up FedoraLinux-43 to $BackupFile..."
wsl --export FedoraLinux-43 $BackupFile

if ($LASTEXITCODE -eq 0) {
    Write-Host "Backup complete: $BackupFile"
    Get-ChildItem "$BackupDir\FedoraLinux-43-*.tar" |
        Sort-Object LastWriteTime -Descending |
        Select-Object -Skip $MaxBackups |
        Remove-Item -Force
    Write-Host "Cleanup done. Keeping last $MaxBackups backups."
} else {
    Write-Host "ERROR: Backup failed!"
}

Register the Scheduled Task

Run in PowerShell as Administrator:

$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
    -Argument "-NonInteractive -File C:\Users\majli\Scripts\backup-wsl.ps1"
$Trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2am
$Settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -RunOnlyIfNetworkAvailable:$false
Register-ScheduledTask -TaskName "WSL2 Backup - FedoraLinux43" `
    -Action $Action -Trigger $Trigger -Settings $Settings `
    -RunLevel Highest -Force

Restore from Backup

wsl --unregister FedoraLinux-43
wsl --import FedoraLinux-43 D:\WSL\Fedora43 D:\WSL\Backups\FedoraLinux-43-YYYY-MM-DD.tar

Then fix the default user — after import WSL resets to root. See wsl2-instance-migration-fedora43 for the /etc/wsl.conf fix.

Gotchas

  • wsl --export fails with ERROR_SHARING_VIOLATION if WSL is running. The script includes wsl --shutdown before export to handle this. Any active WSL sessions will be terminated — schedule the task for a time when WSL is idle (2am works well).
  • Backblaze picks up D:\WSL\Backups\ automatically if D: drive is in scope — provides offsite backup without extra config.
  • Each backup tar is ~500MB1GB depending on what's installed. Keep MaxBackups at 3 to balance retention vs disk usage.

See Also