Hyper-V - Compact Disk

This script will compact a virtual disk file on a Hyper-V server.
Language:
VBScript
Keywords:
Hyper-V
Code Snippet

Option Explicit
 
Dim HyperVServer
Dim VHDName
Dim WMIService
Dim Msvm_ImageManagementService
Dim Result
Dim Job
Dim InParam
Dim OutParam

'Prompt for the Hyper-V Server to use
HyperVServer = InputBox("Specify the Hyper-V Server to create the virtual machine on:")

'Get name for VHD
VHDName = InputBox("Specify the name of the virtual had disk to compact:")

'Get an instance of the WMI Service in the virtualization namespace.
Set WMIService = GetObject("winmgmts:\\" & HyperVServer & "\root\virtualization")
 
'Get the Msvm_ImageManagementService object
Set Msvm_ImageManagementService = WMIService.ExecQuery("SELECT * FROM Msvm_ImageManagementService").ItemIndex(0)
 
'Setup the input parameter list
Set InParam = Msvm_ImageManagementService.Methods_("CompactVirtualHardDisk").InParameters.SpawnInstance_()
InParam.Path = VHDName
 
'Execute the method and store the results in OutParam
Set OutParam = Msvm_ImageManagementService.ExecMethod_("CompactVirtualHardDisk", InParam)
 
'Check to see if the job completed synchronously
if (OutParam.ReturnValue = 0) then
  Wscript.Echo "The virtual hard disk has been compacted."
elseif (OutParam.ReturnValue <> 4096) then
  Wscript.Echo "The virtual hard disk has not been compacted."
else
  'Get the job object
  set Job = WMIService.Get(OutParam.Job)
 
  'Wait for the job to complete (3 == starting, 4 == running)
  while (Job.JobState = 3) or (Job.JobState = 4)
    Wscript.Echo "Compacting. " & Job.PercentComplete & "% complete"
    WScript.Sleep(1000)
    'Refresh the job object
    set Job = WMIService.Get(OutParam.Job)
  Wend
 
  'Provide details if the job fails (7 == complete)
  if (Job.JobState <> 7) then
    Wscript.Echo "The virtual hard disk has not been compacted."
    Wscript.Echo "ErrorCode:" & Job.ErrorCode
    Wscript.Echo "ErrorDescription:" & Job.ErrorDescription
  else
    Wscript.Echo "The virtual hard disk has been compacted."
  end If
end if


Created 2012-02-06
comments powered by Disqus
Login