You should run PowerShell as Administrator (otherwise diskpart
won't be able to received the piped commands)
$vhdx_path = '%USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\ext4.vhdx'
@"
select vdisk file=$vhdx_path
compact vdisk
"@ | diskpart
source: https://stackoverflow.com/questions/64772243/can-diskpart-take-command-line-parameters-or-can-i-fake-them-with-powershell That's all, folks!
If diskpart shows access error, you should run wsl --shutdown
and detach the VHD in Disk Management.
PS: Registered WSL instances are recorded under registry key HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss
. For example, UbuntuonWindows is under HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss\{17e7343c-a823-4a5c-a44d-a795a7546d62}
. You can change the BasePath
to move it to another disk, or change DefaultEnvironment
or KernelCommandLine
to modify how it boot up.
Compacted VHD can be further reduced in size:
# export it to a tar file
wsl --terminate UbuntuonWindows
wsl --export UbuntuonWindows d:\wsl-backup\UbuntuonWindows.tar
# unregister it if you want to import to the same Linux installation
wsl --unregister UbuntuonWindows
# import from tar file
wsl --import UbuntuonWindows d:\path-to\linux-installation-folder d:\wsl-backup\UbuntuonWindows.tar