VMware Cloud Community
daunce
Enthusiast
Enthusiast

Default ordering of output

Hi all.

I'm curious of how powershell/powercli determines the output order. When i assign some variables, and use any get-vm, get-networkadapter for example, the output differs to the order of the array.

Is there any way to keep them in order without losing the speed and doing foreach ($VM in $VMs) {get-vm $VM}.

If I display $VMs to the screen, they appear in the correct order.  In this case I'm working with a single vCenter connection. I've noticed when working with multiple vCenters the output is still in a random order, except grouped together by vCenter.

Using Powershell 4/PowerCLI 5.8 against vCenter 5.0/4.0.

$VMs="VM1","VM2","VM3","VM4","VM5","VM6","VM7","VM8","VM9","VM10"


Get-VM $VMs |select Name

Name

----

VM4

VM10

VM8

VM3

VM6

VM7

VM2

VM9

VM1

VM5

Tags (1)
0 Kudos
3 Replies
LucD
Leadership
Leadership

You can pipe the objects through a Sort-Object cmdlet.

$VMs="VM1","VM2","VM3","VM4","VM5","VM6","VM7","VM8","VM9","VM10"

Get-VM $VMs | Sort-Object -Property Name | Select Name


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

0 Kudos
daunce
Enthusiast
Enthusiast

HI Luc.

Thanks for the reply.

That was a bad example I gave.  The array of VM's aren't in any order. They could be VM3,VM1,VM8,VM5. So then the output would be 8,1,5,3. Whereas I'm after the original order of 3,1,8,5.

Using $VMs shows them in the original order. It's only after they are processed through a cmdlet like get-vm where the order changes.

0 Kudos
vScripter
Contributor
Contributor

Any particular reason you are after such a statically defined output?

The tricky part with maintaining order, here, is that when it goes into Get-VM it's an of strings; once it comes out of Get-VM, the output is a proper object. PowerShell is processing the array in whatever order it pleases.

You could try using a foreach loop to see if that gets what you want, however, it would slow down processing quite a bit, depending on the size of your environment.

Not an elegant solution, but something like this should work; it's essentially a proxy function:

[Also posted on GitHub/Gist]

function Get-OrderedVM {

  [cmdletbinding()]

  param (

  [parameter(Mandatory = $true, Position = 0)]

  [alias('VM')]

  [String[]]$Name

  )

     $finalResult = @()

     foreach ($guest in $vms) {

             $guestQuery = $null

             $guestQuery = Get-VM -Name $guest

             $guestQuery += $finalResult

       } # end foreach $guest

     $finalResult

} # end function Get-OrderedVM

$vms = @('vm1', 'vm3', 'vm2', 'vm4')

Get-OrderedVM -Name $vms

0 Kudos