Skip to content

Instantly share code, notes, and snippets.

@tgran2028
Last active June 18, 2024 22:48
Show Gist options
  • Save tgran2028/42d12ff83295ff4d5d9ad7203f3052bf to your computer and use it in GitHub Desktop.
Save tgran2028/42d12ff83295ff4d5d9ad7203f3052bf to your computer and use it in GitHub Desktop.
Export all WSL distribtions (minus docker images) to tarballs
<#
.SYNOPSIS
Exports WSL distributions to tar.gz files, excluding built-in docker distributions.
.PARAMETER None
.EXAMPLE
.\export-wsl-images.ps1
Exports all WSL distributions to tar.gz files.
.NOTES
Author:Tim Gran
Date: 2024-06-18
#>
# set location to script directory
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
Set-Location -Path $scriptPath
# Install Wsl Module if not installed
if (!((Get-Module -ListAvailable | Select-Object -ExpandProperty Name) -contains 'wsl')) {
Install-Module -Name Wsl -Force -Scope CurrentUser -AllowClobber
}
# Import Wsl Module
Import-Module -Name Wsl -Force
# Stop all WSL Distributions
Get-WslDistribution -State Running | ForEach-Object {
Stop-WslDistribution -Distribution $_ | Out-Null
}
############################################################################################
## Stop-WslDistribution may not work if distribution is in use by another process (e.g. open shell, remote WSL in VS Code, etc.)
## Steps below will wait for 10 seconds for all distribtuions to stop. If not, script will exit.
############################################################################################
# Wait 10 seconds for all WSL Distributions to stop
1..10 | ForEach-Object {
# Check if all stopped. If yes, break, else sleep for 1 second
if ((Get-WslDistribution -State Running).Count -eq 0) {
break
} else {
Start-Sleep -Seconds 1
}
# Raise Error if WSL Distributions are still running after 10 seconds
if ($_ -eq 10) {
Write-Host "Not all WSL Distributions are stopped. Exiting..."
Exit
}
}
# Stop WSL Service
Stop-Wsl
# Get WSL Distributions where 'docker' not in Name
Get-WslDistribution | Where-Object { $_.Name -notlike '*docker*' } | ForEach-Object -Parallel {
$Distro = $_
$OutFile = "$($Distro.Name).$(Get-Date -Format 'yyyyMMdd-HHmmss').tar.gz"
Write-Host "Exporting $($Distro.Name) to $OutFile"
Export-WslDistribution -Distribution $Distro -Destination $OutFile -Format Tar -Verbose
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment