Faster Trimming & Compacting of Hyper-V Ubuntu VMs

A while ago I described how to compact an Ubuntu VHDX running on Hyper-V using the sfill command. Running sfill, however, can take hours. Luckily, there is a much faster alternative.

ubuntu-vm-after-compacting

Ubuntu Trim and Hyper-V

Ubuntu running in a Hyper-V virtual machine has been supporting the trim command since version 14.04 (details). The OS issues trim commands when files are deleted to tell the disk that the blocks occupied by the files can be used elsewhere.

This mechanism originally developed for SSDs is useful for virtual hard disks, too. The host OS (the hypervisor) cannot know when blocks are ready to be reused unless the VM tells it. That is exactly what the trim command is for!

Trimming from Inside the Ubuntu VM with Fstrim

To tell the hypervisor which blocks can be reused issue the following command:

sudo fstrim -v /

This should not take too long.

Compacting the Ubuntu VM’s Virtual Hard Disk (VHDX)

To actually free the space you got back from the trim command above you need to shut down the Ubuntu VM. Then run the following PowerShell code on the Hyper-V machine hosting the Ubuntu VM:

gci -File -Filter *.vhd* -Path D:\VMs -Recurse | % {Mount-VHD $_.FullName -ReadOnly; Optimize-VHD $_.FullName -Mode full; Dismount-VHD $_.FullName}

This should not take too long, either. It recursively searches a base path (D:\VMs) and optimizes each VHD or VHDX file it finds. Adjust the base path as needed. That’s it - enjoy the freed disk space! In my case, the size of the VHDX was reduced from 103 to 31 GB. Not bad for a few minutes of work (and downtime).

Comments

Related Posts

Latest Posts

Beautiful Slide Decks from Markdown: Presenting with Slidev

Beautiful Slide Decks from Markdown: Presenting with Slidev
Would you like to get away from PowerPoint and author slide decks in Markdown? Then Slidev may be just what you’re looking for. It’s a web app for presentations. The fact that it’s geared towards developers shouldn’t put you off. After all, who isn’t a developer these days, with AI? Slidev comes with the beautiful Tahta themes and supports features like syntax highlighting and animations. Export options to PDF and PPTX allow for easy sharing. This article shows how to get started.
Applications