VMware Cloud Community
markdjones82
Expert
Expert

Get-VM foreach loop slow?

All,

  I have a list of VM names I am trying to get name and hardware, but this command runs really slow.  Why?

$vmlist get-content list.txt

$vmlist | % { get-vm -name $_ |select Name,Version | where {$_.version -eq "v7"}
http://www.twitter.com/markdjones82 | http://nutzandbolts.wordpress.com
Reply
0 Kudos
6 Replies
mattboren
Expert
Expert

Hello, markdjones82-

Your overall code is probably slow due to the manner in which you are using Get-VM.  You are calling Get-VM once for every VM in your list of VM names (I assume that your first line of code has a typo, that it is missing the "=" between $vmlist and Get-Content).

Since Get-VM will accept an array of VM names, you can just pass them all in as one value to -Name, and, so, call Get-VM just one time.  Like:

$arrVmlist = Get-Content list.txt
## call Get-VM just one time, passing all VM names in at once
Get-VM -name $arrVmlist | Select Name,Version | Where-Object {$_.Version -eq "v7"}

Say you have 1000 names in your list of VM names.  The original way that you wrote it would call Get-VM 1000 times.  Using this way will call Get-VM one single time.

To give an idea of the speed up, I tested each way with about 100 VMs.  It took about 8.5 seconds the first way (100 Get-VM calls).  It took about 0.3 seconds this way (one Get-VM call).  That's about 28 times faster.  Not bad for just a minor (but important) change to the way it is written.  And, that speed increase should grow as the number of VM names in your list increases.

So, yes, it is pretty important for speed to look for those types of parameters that will take an array of values, rather than having to call the cmdlet one time for every item on which you are acting.

That do any better for you?

LucD
Leadership
Leadership

Quick remark, you can make execution time a bit shorter by placing the filter (Where-clause) before the data handling (Select).

Get-VM -name $arrVmlist | Where-Object {$_.Version -eq "v7"} | Select Name,Version 

There will be the same or less objects presented to the Select-Object cmdlet.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
markdjones82
Expert
Expert

Ah, make sense, pass multiple objects to the one command thanks for the tips guys

http://www.twitter.com/markdjones82 | http://nutzandbolts.wordpress.com
Reply
0 Kudos
mattboren
Expert
Expert

Good point, Luc, thanks for adding it.

Reply
0 Kudos
markdjones82
Expert
Expert

One more quesiton, how do you know if a parameter can take multiple objects and if it does take mutliple objects how are they delimited by a comma or space?

http://www.twitter.com/markdjones82 | http://nutzandbolts.wordpress.com
Reply
0 Kudos
LucD
Leadership
Leadership

Use the Get-Help cmdlet with the Parameter parameter.

the separator is a comma


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos