Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
PowerShell script to compact VHD's in bulk without any user intervention.
Note: Fields that need to be modification - vhd location and machine name.
$strComputers = @(
"F:\VMStore\machine1.vhd",
**"F:\VMStore\machine2.vhd",
"F:\VMStore\machine3.vhd",
**)
foreach($files in $strComputers)
{
$ImageManagementService = gwmi Msvm_ImageManagementService -namespace "root\virtualization" -computername machinename
$result = $ImageManagementService.CompactVirtualHardDisk($files)
if ($Result.ReturnValue -eq 0)
{write-host "The virtual hard disk has been compacted."}
#If the return value is not "0" or "4096" then the operation failed
ElseIf ($Result.ReturnValue -ne 4096)
{write-host "The virtual hard disk has not been compacted. Error value:" $Result.ReturnValue}
Else
{#Get the job object
$job=[WMI]$Result.job
#Provide updates if the jobstate is "3" (starting) or "4" (running)
while ($job.JobState -eq 3 -or $job.JobState -eq 4)
{write-host "Compacting. "$job.PercentComplete "% complete"
start-sleep 1
#Refresh the job object
$job=[WMI]$Result.job}
#A jobstate of "7" means success
if ($job.JobState -eq 7)
{write-host "The virtual hard disk has been compacted."}
Else
{write-host "The virtual hard disk has not been compacted."
write-host "ErrorCode:" $job.ErrorCode
write-host "ErrorDescription" $job.ErrorDescription}
}
}
Save the code as .ps1 and run it from within elevated PowerShell prompt. Make sure the virtual machines are off before executing the script.
The script should indicate compact progress as below:
Compacting. 0 % complete
Compacting. 0 % complete
Compacting. 10 % complete
Compacting. 10 % complete
Compacting. 10 % complete
Compacting. 10 % complete
Compacting. 10 % complete
Compacting. 10 % complete
When it finishes:
The virtual hard disk has been compacted.
You may see the following error if the machine is turned on:
The virtual hard disk has not been compacted.
ErrorCode: 32774
ErrorDescription Failed to compact the virtual disk.
The system failed to compact 'F:\VMStore\machine2.vhd': The process cannot access the file because it is being used by another process.(0x80070020).
Note: The above script is a modification of http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/06/11/hyper-v-script-compact-vhd.aspx