On my hyper-v lab, I have often free space problems because I want to create a lot of Virtual Machines but I have not enough storage. Of course I have created all my VHDX in dynamic to try to save space but this has not been enough. So I said to myself: “Romain why do you not trying to compact VHDX ?”
Then I tried to compact a VHDX of a VM and guess what ? I saved 10GB on only one VHDX ! Because I’m a lazy guy, I begin to look PowerShell command to run a compacting process on every VHDX. To compact a VHDX you can run the below PowerShell command:
Optimize-VHD -Path <Path-To.vhdx>
The only problem with this command is that the Virtual Machine must be stopped to run the compacting. When the virtual machine is running, the VHDX is hold by its virtual machine.
So I have written a script that connect to the Hyper-V, verify if the VM is running, and if this last is stopped, all VHDX are compacted. I have called this script VHD optimizer. But be careful it’s still a beta.
To run my script you can use the below parameters:
- VMHostName: Hyper-V host where you want run the compacting process
- WorkingFolderValue: Where will be stored html report and log file
- PrefixValue: this is to set a prefix string for the html report and the log file
- HTMLReportState ($True or $False): set to $true to enable the HTML Report
- Mail ($True or $False): set to $true to send the report by E-mail
- AutoStopState ($True or $Flase): set to $True to automatically stop VM to run the compacting
Next don’t forget to edit SMTP variables inside the script if you want to send the HTML report by E-mail.
Example of using:
.\Optimize-VHD.ps1 -VMHostName HyperV01 -WorkFolderValue c:\temp -PrefixValue Infra -HTMLReportState $true -AutoStopState $True -Mail $False
Because it is a beta, it will be great if you could send me by E-mail bugs or suggestions :).