2010-04-11

Small Quirk with Get-View vs. Get-VM

I was trying something last night to compare the speed of the two Cmdlets here.

I noticed something though.

While running the command I wanted to check against how many machines I was running the command against.

Get-View -ViewType VirtualMachine | Measure-Object

Count    : 371


And compared to

get-vm | Measure-Object

Count    : 356


And as you can see they are not the same! The reason for that being that Get-VM does not retrieve any templates only virtual machines. To get the Template you need to get them specifically

Get-Template | Measure-Object

Count    : 15


And adding the results from above to the ones from Get-VM will give me the same amount of machines that I got from the first Command.

So how would you get only the Virtual Machines (and not templates)? You can add a filter to the command

Get-View -ViewType VirtualMachine -Filter @{"Config.Template"="false"} | Measure-Object

Count    : 356


But so that you know, the filtering adds some overhead to the time it takes to run the command.

$filtered = (Measure-command {Get-View -ViewType VirtualMachine -Filter @{"Config.Template"="false"} | Measure-Object}).TotalSeconds
$filtered
8.3746321
$notfiltered = (Measure-command {Get-View -ViewType VirtualMachine}).TotalSeconds
$notfiltered
8.03360323

As you can see the filtered query is slower even though it processes less objects. Now you might say this is negligible - it is. But the bigger your environment is the more substantial this can become.

So sometimes even though you want to make your life easier by filtering to get only what you would like - it does not always optimize your scripts.