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:



3 responses

  1. Hugo

    Hi ! I know it may look stupid, but I got the following error:
    “Unable to mont disk V:\………… .. stopping”
    Any clue on what’s doing that?
    Please note that I successfully mounted the volume from Explorer.

    November 6, 2015 at 11:51 am

    • Hugo

      OK, nvm it’s because I don’t have HV role installed on that machine -_-

      November 6, 2015 at 11:54 am

  2. user135711

    Using the hypervisor administrator in 2016 server, the time expensive sdelete step, or zeroing free space is no longer necessary. I just ran disk compact after deleting 150gb without zeroing anything and the size on disk was compacted to the 38GB’s stored on disk and the virtual disk size unchanged.

    September 28, 2017 at 5:47 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.