VMware – Determining ownership of a virtual disk using PowerShell

Tuesday, 29. June 2010

So as you may have guessed, I work with VMware a bit in my employment. On top of that, I’ve tried to start using PowerShell to automate repetitive tasks that I run into. (In fact, one of the major points of the existence of this page is to give myself a location to store these findings in a place which I can find them later, and if someone else finds them useful, then great.)

Anyway, the problem I ran into today was that I had a VM on a datastore whose name did not match a VM in my vCenter inventory. How could I tell if these files were in use by a legitimate VM or just wasting space? I could right-click and ‘Edit Settings’ on hundreds of VM’s… or I could use Powershell.

so I started off by connecting to the vCenter server and getting an inventory of VM’s:

Connect-VIServer servername
$VM = Get-VM

Then I grabbed a list of disks which matched my criteria:

$Disks = $VM | Get-HardDisk | Where {$_.FileName -like '*web*' }

Then I did…

$Disks | Get-Member and saw that there are Name, FileName, and ParentID properties. By doing $Disks | Select Name, FileName, ParentID,  I now have the parent Id of the VM.

So how do I know which VM the parent ID field references?

$VM | Where {$_.Id -like 'parent id from previous select'}

… which returns ….

Name PowerState Num CPUs Memory (MB)
---- ---------- -------- -----------
WebSrv1 PoweredOn 4 4096

Is there an easier way to do this? Probably, and I already have a couple of ideas. If I can get them working and cleaned up, I’ll post them here.

Leave a Reply