How to Compact WSL 2 Virtual Hard Disks (VHDX) in Windows 11 Using PowerShell

Windows Subsystem for Linux (WSL 2) stores distribution file systems within dynamically expanding Virtual Hard Disk (ext4.vhdx) containers. As developers clone large Git repositories, install complex Python machine learning models, or build Docker images, the VHDX file expands dynamically on the Windows host drive. However, deleting files inside Linux does not automatically shrink the host .vhdx file, leading to severe host storage exhaustion. Performing manual or automated VHDX compaction via PowerShell reclaims dozens of gigabytes of host disk space.

Understanding VHDX Storage Bloat

The discrepancy between Linux storage usage and Windows file size stems from virtual disk architecture:

  • Ext4 Allocation: When files are written in Linux, the ext4 file system requests new storage blocks, causing Windows to expand the underlying ext4.vhdx file.
  • Zero-Fill Requirement: When files are deleted inside Linux, ext4 marks those blocks as free, but the host VHDX container retains the allocated physical disk space until unused blocks are zeroed and compacted.
  • Modern Solution: Windows 11 supports both Diskpart compaction routines and native wsl --manage --set-sparse flags to maintain compact disk footprints.

Compacting WSL 2 VHDX via Diskpart in PowerShell

To reclaim unallocated storage space from an existing distribution disk:

  1. Open an elevated PowerShell prompt as Administrator.
  2. Shut down the WSL virtual machine to release all active file locks:
    wsl --shutdown
  3. Locate the distribution’s ext4.vhdx file path (typically under $env:LOCALAPPDATA\Packages\CanonicalGroupLimited...\LocalState\ext4.vhdx).
  4. Launch Diskpart and execute compaction commands programmatically:
    # Define VHDX file path
    $vhdxPath = "$env:LOCALAPPDATA\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\ext4.vhdx"
    
    # Construct Diskpart script payload
    $diskpartScript = @"
    select vdisk file="$vhdxPath"
    attach vdisk readonly
    compact vdisk
    detach vdisk
    "@
    
    # Execute Diskpart compaction
    $diskpartScript | diskpart
    Write-Host "VHDX compaction completed successfully." -ForegroundColor Green
  5. Diskpart attaches the virtual disk in read-only mode, scans for unallocated blocks, and shrinks the physical container file to match actual data usage.

Enabling Continuous Sparse Reclamation

To avoid manual Diskpart maintenance in the future, convert the virtual disk to a native sparse VHD:

wsl --manage Ubuntu --set-sparse true

Compacting WSL 2 virtual disks in Windows 11 recovers critical host storage space, ensuring peak workstation drive efficiency.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.