How can I compact the VHD file with Ubuntu?

Poweroff your VM, backup the VHD, and run another virtual machine (I use SystemRescueCD since it's small and fast) that has the ext4 partition available to it, i.e., a HD for SysRescue (but don't mount it!). From the SysRescue VM, run 'zerofree' on the ext4 partition, poweroff that VM, and then use your Administration Website to compact the VHD.


I can confirm: zerofree is working to compact virtual disk files

BUT: you don't need to use any rescue CDs or to mount the VHDX in another virtual machine:

sudo apt-get install zerofree

Boot in safe mode, then run:

zerofree /dev/sda1

After that, we have to start the optimization for the virtual disk file. On the server hosting the VHDX file, create the following file ShrinkVhdx.ps1:

[CmdletBinding()]
Param(
    $VHDFiles
)

    #Find the disks
    foreach($VHD in $VHDFiles){
        Write-Verbose "Working on $VHD, please wait"
        Write-Verbose "Current size $([math]::truncate($(Get-VHD -Path $VHD).FileSize/ 1GB)) GB"
        Mount-VHD -Path $VHD -NoDriveLetter -ReadOnly
        Optimize-VHD -Path $VHD -Mode Full
        Write-Verbose "Optimize size $([math]::truncate($(Get-VHD -Path $VHD).FileSize/ 1GB)) GB"
        Dismount-VHD -Path $VHD
        Write-Verbose ""
        }

And now run the file and enjoy the released disk space :-)

ShrinkVhdx.ps1 .\hdd1.vhdx