2

Reading the WSL documentation and the one of the Windows command line wsl.exe, I have not found any mean to get the size of a WSL distribution from the Windows command line.

I know it is quite easy from the distribution command line itself cf here, but how to get it from the Wndows command line?

1

1 Answer 1

1

It's certainly easiest to find the path of the distribution and just view it in Explorer, but for a purely command-line approach, which is what you requested ...

From Windows PowerShell or PowerShell Core:

Get-ChildItem "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss" -Recurse |
ForEach-Object {
    $distro_name = ($_ | Get-ItemProperty -Name DistributionName).DistributionName
    $distro_dir =  ($_ | Get-ItemProperty -Name BasePath).BasePath
    $distro_dir = Switch ($PSVersionTable.PSEdition) {
      "Core" {
        $distro_dir -replace '^\\\\\?\\',''
      }
      "Desktop" {
        if ($distro_dir.StartsWith('\\?\')) {
            $distro_dir
        } else {
            '\\?\' + $distro_dir
        }
      }
    }
    Write-Output "------------------------------"
    Write-Output "Distribution: $distro_name"
    Write-Output "Directory: $($distro_dir -replace '\\\\\?\\','')"
    $distro_size = "{0:N0} MB" -f ((Get-ChildItem -Recurse -LiteralPath "$distro_dir" | Measure-Object -Property Length -sum).sum / 1Mb)
    Write-Output "Size: $distro_size"
}

Will report the Name, Directory, and Size for each WSL Distribution.

Explanation:

  • Parses the registry entries for WSL distributions to retrieve their name and base directory
  • Some WSL distributions (those created with wsl --import, I believe) have directory names that start with \\?\, the Windows long-path prefix. This is problematic since Windows PowerShell and PowerShell Core treat these paths differently. The if and switch conditionals (and the -replace) in the script are there so that it works on both versions.
  • Once we have a consistent directory name (that works with long paths on all platforms), we can recurse through them and use PowerShell's Measure-Object cmdlet to sum the sizes of all files.
  • This will work for both WSL1, where the Linux files are directly stored on the filesystem, and WSL2, where the files are in virtual drives.

Side note:

I know it is quite easy from the distribution command line itself

Not really. The answer you linked to was written before WSL2 was released. It works for WSL1, but WSL2 distributions are stored in a Windows .vhdx (virtual disk) that grows as needed, but does not shrink when files in it are deleted.

For that reason, with WSL2, something like ncdu (from the question you linked) will only report the size that the distribution thinks is being used. The actual size of the virtual disk on the Windows drive could be (sometimes much) larger.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .