Coding Corner: Compacting a virtual hard disk

Today I am going to go over a basic script for compacting a virtual hard disk.  This script creates a virtual hard disk object from a string that points to the virtual hard disk file (in the script this information is provided as a command line parameter).  The script then executes the ‘compact’ method – which returns a VMTask object.  We can then use this VMTask object to monitor the progress of the compaction:

‘Script Begins

On Error Resume Next

‘Connect to Virtual Server and check for failure
Set virtualServer = CreateObject(“VirtualServer.Application”)
If Err.number <> 0 Then error(“Failed to connect to Virtual Server”)

‘Connect to virtual hard disk (provided as command line parameter) and check for failure
Set aVirtualHardDisk = virtualServer.GetHardDisk(WScript.Arguments(0))
If Err.number <> 0 Then error(“Failed to connect to virtual hard disk”)

‘Start compaction process and check for failure
Set compactionTask = aVirtualHardDisk.Compact
If Err.number <> 0 Then error(“Failed to compact virtual hard disk”)

‘Display task description
wscript.echo compactionTask.Description

‘Loop waiting for task completion – and display status
while not compactionTask.isComplete
   wscript.echo “Compaction is ” & compactionTask.PercentCompleted & “% complete”
   WScript.Sleep 2000

wscript.echo “Compaction complete”

‘Pause before exiting
WScript.Sleep 5000

‘Generic error handler
sub error(message)

   wscript.echo message
   wscript.echo Err.Description
   WScript.Sleep 5000
end sub

‘Script Ends

As there are a couple of areas where you could hit a problem – I have put in some basic error handling to explain why things fail.  Also – it should be noted that while this script will request that the virtual hard disk is compacted – the actual compaction is done by Virtual Server.  This means that if you close the command prompt window while the script is running – Virtual Server will continue to compact the virtual hard disk in the background.