Consolidating unmounted and open snapshots after virtual machine backup

At times, one or more disks from a virtual machine will remain mounted and snapshots will remain following the backup of a virtual machine. The cause of this is generally due to their not being enough time to unmount the disks and consolidate the snapshots when the job completes.

This would require user interaction to firstly unmount the virtual machine disks and then perform a consolidation of the virtual machine virtual disks. As we can agree, this is a manual task that is perfect to be automated.

The below solution has a number of caveats, the backup solution/appliance is a virtual machine and the virtual machine contains no hard disks that are of the disk type ‘Independent – Nonpersistent’.

The script in its entirety can be downloaded from here. However, the below will describe the logic to remove the virtual machine hard disks and consolidate the virtual machines.

Once we have established a connection to the vCenter Server and specified the virtual machine running the backup appliance/solution we will retrieve a collection of virtual machines where the ‘RunTime.ConsolidatedNeeded’ value is equal to ‘True’.

$VMs = Get-View -ViewType VirtualMachine -Property Name, RunTime | Where-Object {$_.RunTime.ConsolidationNeeded -eq $True}

Then we will connect to the virtual machine hosting the backup appliance/solution and retrieve all the virtual machine hard disks where the persistence value is equal to ‘IndependentNonPersistent’.

$HardDisks = Get-VM $ComputerName | Get-HardDisk | Where-Object {$_.Persistence -eq 'IndependentNonPersistent'} 

We will then invoke the Remove-HardDisk cmdlet to remove the filtered virtual machine hard disks. In this instance we are only removing the hard disks and not deleting them permanently.

Get-HardDisk -VM $ComputerName -Name $HardDisks.Name | Remove-HardDisk -Confirm:$False

Once the virtual machine hard disks have been removed, we will now consolidate the virtual machine disks on each of the virtual machines returned in the collection.

(Get-VM $VM.Name).ExtensionData.ConsolidateVMDisks() | Out-Null

The above script will provide console output to report the status of the invocation and can be triggered as a scheduled task returning an exit return code dependant on the status of the invocation.


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 )

Connecting to %s