A quick way to find virtual machines with incorrect names

A few days back I saw a twitter post from @maishsk which linked to this article:


The article got me thinking about the difference between Get-VM and Get-View and I wanted to apply it to a script I’ve been using for a little while.  This is a pretty simple script that finds my virtual machines that have incorrect names — the host name inside the VM doesn’t match the name of the VM in the vCenter console.

Using the Get-VM cmdlet takes 148.7862461 seconds to find all of my virtual machines (excluding the templates):
[cc lang=”powershell”]$getvms = (Measure-Command {get-vm | where { $_.Guest.HostName -ne $NULL -AND $_.Guest.HostName -notmatch $_.Name } | select-object name, {$_.Guest.HostName}}).TotalSeconds[/cc]

Using the Get-View VirtualMachines cmdlet with a filter to exclude templates only takes 11.6853342 seconds:
[cc lang=”powershell”]$getviewf = (Measure-Command {get-view -viewtype virtualmachine -Filter @{“Config.Template”=”false”} | where { $_.Guest.HostName -ne $NULL -AND $_.Guest.HostName -notmatch $_.Name } | select-object name, {$_.Guest.HostName}}).TotalSeconds[/cc]

While either script does a better job than trying to compare these settings manually, this Get-View method shows a very significant savings!  Thanks for the suggestion @maishsk!

Just in case you only want the query to show VM’s with incorrect names, here you go:

[cc lang=”powershell”]get-view -viewtype virtualmachine -Filter @{“Config.Template”=”false”} | where { $_.Guest.HostName -ne $NULL -AND $_.Guest.HostName -notmatch $_.Name } | select-object name, {$_.Guest.HostName}[/cc]

This entry was posted in Scripting, Virtualization. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


Notify me of followup comments via e-mail. You can also subscribe without commenting.