How to Speed Up Your PowerCLI Queries

It is a known fact that using PowerCLI there are more than one way to skin a cat - or more than one way to access the SDK and the properties that you would like to get.

Take for example getting all the VM’s - their Name, their Memory and CPU count

Measure-command {get-vm | ForEach-Object { Write-host $_.Name $_.MemoryMB $_.NumCpu } } | select TotalSeconds

TotalSeconds
------------
5.402703

You can also get the same thing with the Get-View cmdlet

measure-command {Get-View -ViewType VirtualMachine | ForEach-Object { Write-host $_.Name $_.Config.Hardware.memoryMB $_.Config.Hardware.numCPU }} | select TotalSeconds

TotalSeconds
------------
11.1451083

Now of course you can speed this up with only getting the attributes you want like this

Measure-command {get-vm | select Name, MemoryMB, NumCPU | ForEach-Object { Write-host $_.Name $_.MemoryMB $_.NumCpu } } | select TotalSeconds

TotalSeconds
------------
5.0431041

But you can also get the same with get-view but this time running the query only getting the properties that you want

measure-command {Get-View -ViewType VirtualMachine -property Name,Config.Hardware | ForEach-Object { Write-host $_.Name $_.Config.Hardware.memoryMB $_.Config.Hardware.numCPU }} | select TotalSeconds

TotalSeconds
------------
3.8932184

Whoa - that was 1.5094846 seconds difference or 38.77% faster.

Lessons learned from this one?

  1. As you can see from Example 2 - not always is Get-View faster
  2. In some cases - (and you have to test this!) Get-View can be much, much faster

Thanks to LucD and Keshav Attrey for the info from this forum thread