Windows Server 2012/R2: compattazione vhd dinamici

Talvolta può accadere di dover compattare dei dischi virtuali vhd/vhdx di VM perché a seguito del normale funzionamento questi hanno assunto dimensioni elevati che però sono di fatto molto superiori al reale spazio occupato.

Di seguito la procedura che è necessario eseguire per ridurre al massimo il file vhd/vhdx:

Passo 1: Deframmentare il disco avviando la procedura di deframmentazione all’interno dell’OS della VM

Passo 2: Arrestare la macchina virtuale

Passo 3: Montare il vhd/vhdx in read only tramite interfaccia grafica dell’applet Disk Management o tramite il cmdlet PowerShell Mount-VHD:

Mount-Vhd –path <Path del file vhd/vhdx> -readonly

Passo 4: Eseguire una compattazione  tramite l’interfaccia grafica dell’applet Hyper-V manager o tramite il cmdlet PowerShell Optimize-VHD:

Optimize-Vhd -path <Path del file vhd/vhdx> -Mode Full

Passo 5: Disconnettere il vhd/vhdx in read only tramite interfaccia grafica dell’applet Disk Management o tramite il cmdlet PowerShell Dismount-VHD:

Dismount-vhd -path <Path del file vhd/vhdx>

Come riportato nella sezione TechNet del cmdlet Optimize-VHD il file vhd/vhdx non deve essere montato o montato in readonly:

“This operation reclaims unused blocks as well as rearranges the blocks to be more efficiently packed, which reduces the size of a virtual hard disk file.

To use Optimize-VHD, the virtual hard disk must not be attached or must be attached in read-only mode.

The compact operation can succeed without reducing the file size, if no optimization is possible.”

Per utilizzare l’opzione Full di compattazione è però necessario che il  file vhd/vhdx sia montato in modalità readonly:

“Full scans for zero blocks and reclaims unused blocks. (Allowable only if the virtual hard disk is mounted read-only.)”

Concludendo per compattare un file vhd/vhdx è necessario che questo sia montato in modalità read only.

Per ulteriori informazioni si veda anche il post Compacting a Dynamically Expanding virtual hard disk in Windows Server 2012 e in particolare la nota relativa a dischi virtuali non formattati in NTFS:

“It is still recommended that you defrag the drive in advance. Also be aware, if the virtual hard disk is not NTFS formatted, you must prepare the virtual hard disk for compacting by using a non-Microsoft disk utility program to replace the blank space with zeroes. Lastly, the vhd cannot be in use.”