[CmdletBinding()]
param(
[string[]]$DistroName,
[switch]$AllDistros,
[switch]$IncludeDocker,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$lxssRegistryPath = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss'
function Test-IsAdministrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Get-FileSizeGiB([string]$Path) {
if (-not (Test-Path -LiteralPath $Path)) {
return $null
}
return [math]::Round((Get-Item -LiteralPath $Path).Length / 1GB, 2)
}
function Get-SystemDriveFreeGiB {
$driveName = $env:SystemDrive.TrimEnd(':')
return [math]::Round((Get-PSDrive -Name $driveName).Free / 1GB, 2)
}
function ConvertTo-NormalWindowsPath([string]$Path) {
$expanded = [Environment]::ExpandEnvironmentVariables($Path)
if ($expanded.StartsWith('\\?\')) {
return $expanded.Substring(4)
}
return $expanded
}
function Get-WslDistributions {
if (-not (Test-Path -LiteralPath $lxssRegistryPath)) {
throw 'No WSL distributions were found for the current Windows user.'
}
$rootKey = Get-Item -LiteralPath $lxssRegistryPath
$defaultDistribution = [string]$rootKey.GetValue('DefaultDistribution')
$distributions = @()
foreach ($key in Get-ChildItem -LiteralPath $lxssRegistryPath) {
$distributionName = [string]$key.GetValue('DistributionName')
$distributionBasePath = [string]$key.GetValue('BasePath')
if (-not $distributionName -or -not $distributionBasePath) {
continue
}
$version = [int]$key.GetValue('Version', 1)
if ($version -ne 2) {
continue
}
$basePath = ConvertTo-NormalWindowsPath $distributionBasePath
$vhdPath = Join-Path $basePath 'ext4.vhdx'
if (-not (Test-Path -LiteralPath $vhdPath)) {
continue
}
$distributions += [pscustomobject]@{
Name = $distributionName
VhdPath = $vhdPath
IsDefault = [string]$key.PSChildName -ieq [string]$defaultDistribution
}
}
return @($distributions | Sort-Object Name)
}
function Select-WslDistributions {
param(
[object[]]$Distributions,
[string[]]$RequestedNames,
[bool]$SelectAll
)
if ($SelectAll -and $RequestedNames.Count -gt 0) {
throw 'Use either -AllDistros or -DistroName, not both.'
}
if ($SelectAll) {
return @($Distributions)
}
if ($RequestedNames.Count -gt 0) {
$selected = @()
foreach ($name in $RequestedNames) {
$match = @($Distributions | Where-Object { $_.Name -ieq $name })
if ($match.Count -ne 1) {
$available = ($Distributions.Name -join ', ')
throw "WSL 2 distro '$name' was not found. Available: $available"
}
$selected += $match[0]
}
return @($selected)
}
$default = @($Distributions | Where-Object { $_.IsDefault })
if ($default.Count -eq 1) {
return $default
}
if ($Distributions.Count -eq 1) {
return @($Distributions[0])
}
$available = ($Distributions.Name -join ', ')
throw "No default WSL 2 distro could be resolved. Pass -DistroName or -AllDistros. Available: $available"
}
function Get-DockerVhdPath {
$candidates = @(
(Join-Path $env:LOCALAPPDATA 'Docker\wsl\disk\docker_data.vhdx'),
(Join-Path $env:LOCALAPPDATA 'Docker\wsl\data\ext4.vhdx')
)
foreach ($candidate in $candidates) {
if (Test-Path -LiteralPath $candidate) {
return $candidate
}
}
return $null
}
if (-not (Get-Command wsl.exe -ErrorAction SilentlyContinue)) {
throw 'wsl.exe was not found. This script requires WSL 2 on Windows.'
}
if (-not (Test-IsAdministrator)) {
Write-Host 'Requesting administrator permission...'
$stagedScript = Join-Path $env:TEMP 'compact-wsl-vhdx.ps1'
Copy-Item -LiteralPath $PSCommandPath -Destination $stagedScript -Force
$powerShellPath = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
$arguments = @(
'-NoExit'
'-NoProfile'
'-ExecutionPolicy', 'Bypass'
'-File', ('"{0}"' -f $stagedScript)
)
if ($AllDistros) {
$arguments += '-AllDistros'
}
elseif (@($DistroName).Count -gt 0) {
$arguments += '-DistroName'
foreach ($name in $DistroName) {
$arguments += ('"{0}"' -f $name.Replace('"', '\"'))
}
}
if ($IncludeDocker) {
$arguments += '-IncludeDocker'
}
if ($Force) {
$arguments += '-Force'
}
$null = Start-Process -FilePath $powerShellPath -Verb RunAs -WindowStyle Normal -ArgumentList $arguments
exit 0
}
Import-Module Hyper-V -ErrorAction Stop
$allDistributions = @(Get-WslDistributions)
if ($allDistributions.Count -eq 0) {
throw 'No WSL 2 ext4.vhdx files were found for the current Windows user.'
}
$requestedNames = if ($null -eq $DistroName) { @() } else { @($DistroName) }
$selectedDistributions = @(Select-WslDistributions `
-Distributions $allDistributions `
-RequestedNames $requestedNames `
-SelectAll $AllDistros.IsPresent)
$targets = @()
foreach ($distribution in $selectedDistributions) {
$targets += [pscustomobject]@{
Kind = 'WSL'
Name = $distribution.Name
Path = $distribution.VhdPath
SizeBeforeGiB = Get-FileSizeGiB $distribution.VhdPath
}
}
$dockerCommand = $null
$dockerVhdPath = $null
if ($IncludeDocker) {
$dockerCommand = Get-Command docker.exe -ErrorAction SilentlyContinue
if (-not $dockerCommand) {
throw 'Docker Desktop CLI was not found. Remove -IncludeDocker or install Docker Desktop.'
}
$dockerVhdPath = Get-DockerVhdPath
if (-not $dockerVhdPath) {
throw 'Docker Desktop WSL data disk was not found.'
}
$targets += [pscustomobject]@{
Kind = 'Docker'
Name = 'Docker Desktop'
Path = $dockerVhdPath
SizeBeforeGiB = Get-FileSizeGiB $dockerVhdPath
}
}
$desktop = [Environment]::GetFolderPath('Desktop')
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$logPath = Join-Path $desktop "compact-wsl-vhdx-$timestamp.log"
$transcriptStarted = $false
$dockerStopped = $false
$failures = @()
$systemDriveFreeBefore = Get-SystemDriveFreeGiB
try {
Start-Transcript -Path $logPath -Force | Out-Null
$transcriptStarted = $true
}
catch {
Write-Warning "Could not start transcript: $($_.Exception.Message)"
}
try {
Write-Host ''
Write-Host 'Targets:'
foreach ($target in $targets) {
Write-Host " $($target.Name): $($target.SizeBeforeGiB) GiB"
Write-Host " $($target.Path)"
}
Write-Host ''
Write-Host 'This script trims free blocks, shuts down WSL, and compacts the selected virtual disks.'
Write-Host 'It does not delete files or prune Docker data.'
Write-Host 'Close WSL terminals, remote editor windows, and Explorer windows open to \\wsl$ before continuing.'
if (-not $Force) {
$answer = Read-Host 'Continue? [y/N]'
if ($answer -notmatch '^(y|yes)$') {
Write-Host 'Cancelled. No changes were made.'
exit 0
}
}
foreach ($distribution in $selectedDistributions) {
Write-Host ''
Write-Host "Trimming free blocks inside $($distribution.Name)..."
& wsl.exe -d $distribution.Name -u root -- fstrim -v /
if ($LASTEXITCODE -ne 0) {
throw "fstrim failed for $($distribution.Name) with exit code $LASTEXITCODE"
}
}
if ($IncludeDocker) {
Write-Host ''
Write-Host 'Stopping Docker Desktop...'
& docker.exe desktop stop
if ($LASTEXITCODE -ne 0) {
throw "Docker Desktop stop failed with exit code $LASTEXITCODE"
}
$dockerStopped = $true
}
Write-Host ''
Write-Host 'Shutting down WSL...'
& wsl.exe --shutdown
if ($LASTEXITCODE -ne 0) {
throw "WSL shutdown failed with exit code $LASTEXITCODE"
}
Start-Sleep -Seconds 5
$runningDistributions = @(& wsl.exe --list --running --quiet 2>$null) |
ForEach-Object { ($_ -replace [char]0, '').Trim() } |
Where-Object { $_ }
if ($runningDistributions.Count -gt 0) {
throw "WSL restarted before compaction. Still running: $($runningDistributions -join ', ')"
}
foreach ($target in $targets) {
try {
$diskImage = Get-DiskImage -ImagePath $target.Path -ErrorAction SilentlyContinue
if ($diskImage -and $diskImage.Attached) {
throw 'The virtual disk is still attached after WSL shutdown.'
}
Write-Host ''
Write-Host "Compacting $($target.Name)..."
$mountedReadOnly = $false
try {
Mount-VHD -Path $target.Path -ReadOnly -NoDriveLetter
$mountedReadOnly = $true
Optimize-VHD -Path $target.Path -Mode Full
}
finally {
if ($mountedReadOnly) {
Dismount-VHD -Path $target.Path
}
}
}
catch {
$message = "$($target.Name): $($_.Exception.Message)"
$failures += $message
Write-Warning $message
}
}
}
catch {
$failures += $_.Exception.Message
Write-Warning $_.Exception.Message
}
finally {
if ($dockerStopped) {
Write-Host ''
Write-Host 'Starting Docker Desktop...'
& docker.exe desktop start
if ($LASTEXITCODE -ne 0) {
$failures += "Docker Desktop start failed with exit code $LASTEXITCODE"
}
}
}
$systemDriveFreeAfter = Get-SystemDriveFreeGiB
Write-Host ''
Write-Host "System drive free before: $systemDriveFreeBefore GiB"
Write-Host "System drive free after: $systemDriveFreeAfter GiB"
Write-Host "Change: $([math]::Round($systemDriveFreeAfter - $systemDriveFreeBefore, 2)) GiB"
Write-Host ''
Write-Host 'Virtual disk sizes:'
foreach ($target in $targets) {
$sizeAfter = Get-FileSizeGiB $target.Path
$change = [math]::Round($target.SizeBeforeGiB - $sizeAfter, 2)
Write-Host " $($target.Name): $($target.SizeBeforeGiB) GiB -> $sizeAfter GiB ($change GiB reclaimed)"
}
$exitCode = 0
if ($failures.Count -gt 0) {
Write-Warning "Completed with $($failures.Count) failure(s)."
foreach ($failure in $failures) {
Write-Warning " $failure"
}
$exitCode = 1
}
else {
Write-Host 'Done.'
}
Write-Host "Log saved to $logPath"
if ($transcriptStarted) {
Stop-Transcript | Out-Null
}
exit $exitCode