Powershell script to reduce dynamic VHDX disk size
Have you ever been in the situation where you have a dynamic VHDX disk where you cleaned up some space by deleting unneeded files, but the VHDX file size on the underlying disk remains the same? Take this example: I started with this test disk:
Then I converted it to dynamic:
Dismount-VHD -DiskNumber 13 -Confirm:$false Convert-VHD -Path 'd:\Fixed1.vhdx' -DestinationPath 'd:\Dynamic1.vhdx' -VHDType Dynamic
Then I copied some files taking about 2.6 GB of the test 4 GB disk:
Then I deleted about 1.9 GB worth of files:
Yet, the VHDX file still takes the same space on the underlying disk:
The following script zeros out unused space on the VHDX file, and compacts it. It can be downloaded from the Microsoft Script Center Repository. The script works on both VHD and VHDX files.
To use it, download the .rar file, decompress it, unblock the 2 files, adjust PS execution policy as needed, run the script to load the function in memory, then use it.
To see help use:
Help Compact-VHDX -Full
Compact-VHDX -VHDXPath D:\Dynamic1.vhdx -SDelete .\sdelete.exe
The disk to be compacted must be dismounted first. If the script is run on a disk that’s already mounted, you’ll get a message like:
Otherwise, the script will run, giving output similar to:
This may take a while depending on the speed of the underlying disk system and the size of the disk being compacted.
When done the output will look like:
The reduced file size can be confirmed in Windows Explorer as well:
Script output is also saved to log file: