Search

Compact VHD file

To compact a VHD file in Windows 7 (Windows Server 2008 R2) and later (Windows 8, Windows Server 2012, Windows Server 2012 R2), do the following:

  • In VM:
    • Delete all temp files
    • Defrag HD (if you run SQL Server stop the service to release DB files)
      • Run Windows Defrag tool first
      • To consolidate free space in HD, you can use the defrag tool MyDefrag (which is free). The 'consolidate free space' script will fragment files in order to fill-in all the gaps (that's OK)
    • To zero out unused space in disk, you can use the SDELETE command line tool from SysInternals
      • Use the command: sdelete -z [drive]:
    • Shutdown the VM
  • In Host (if you don't use Hyper-V):
    • Open a command prompt window with administrator privileges
    • Run the following commands:
      • diskpart
      • select vdisk file="[path to VHD file]"
      • attach vdisk readonly
      • compact vdisk
      • detach vdisk
      • exit
  • In Host (if you use Hyper-V):
    • Use the Hyper-V management console to compact the VHD file.

The VHD file should be compacted.

Note: Before starting the procedure, make sure you backed-up the VHD file. It is not recommended to apply this guide to production environments.