PowerCLI: VM displayName -ne Name

If you were lucky enough to get a hold of @jasonboche vCalendar then this morning you were greeted with a tip regarding the DisplayName of a VM not matching it’s actual path.   As someone who has ran rm -rf  on more than one running vm because of this very issue.**  I will personally attest to why you should care about this!  Jason includes a link to Dominic’s solution in the calendar, but I’m not crazy about perl. So I wrote my own, PowerCLI find any VM with a naming issue.

So what does that do? Well for speed we start with Get-View, and only retrieve the Config property for each VM. Then we pass that collection through Where-Object. This is where PowerShell earns it’s name.

So -match will perform a regular expression comparison operation, So here if the VmPathName looks anything like vm/vm.vmx -match will return $true, and that object will be passed down the pipeline. That however is only part of the story. When PowerShell matches something with a regex it stores the results in $Matches. This means that we can easily look that data up later. In addition I’m naming my matches. if you look in my regex you’ll notice (?<folder>.+?). The ?<folder> will apply the parameter name “folder” to anything that is matched inside the parenthesis, How cool is that!

From there it becomes real easy to see what I’m doing. I compare the displayName with both the Folder name, and the name of the vmx. Then I pass anything that didn’t match to the Get-VIObjectByView Cmdlet.

So how did it do? Well I just scanned 600 VM’s in less than 20 sec, and found two problem children. There you have it, my PowerCLI vCalendar solution for September 10th, 2009! I’m really looking forward to the rest of this calendar, and all the possible automation goodness.


**Note your not screwed if you delete a running VM, take a deep breath, and DON’T power the VM off!  You’ll need to recreate several files, but you have time.  ESX/vSphere have a lock on everything the VM needs to run.

Leave a Reply