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:

convert2

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:

convert3

Then I deleted about 1.9 GB worth of files:

convert7

Yet, the VHDX file still takes the same space on the underlying disk:

convert8

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

Example:

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:

convert9

Otherwise, the script will run, giving output similar to:

convert10

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:

convert11

The reduced file size can be confirmed in Windows Explorer as well:

convert12

Script output is also saved to log file:

convert13

Advertisements

2 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

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s