VMware Cloud Community
KRAEMS
Enthusiast
Enthusiast

Sorting IP addresses

Hello Experts,

Wondering if anyone has a 'true' way to sort IP addresses... I do have:

Get-VM -Location $datacenter | where {$_.guest.IPAddress[0] -like "x.y.z*"} | Select @{N="IP Address";E={@($_.guest.IPAddress[0])}} | Sort -Property "IP Address"

Results in:

.

.

.

x.y.z.158

x.y.z.16

x.y.z.160

x.y.z.163

x.y.z.164

x.y.z.165

x.y.z.17

x.y.z.170

x.y.z.175

.

.

.

What I desire would return:

.

.

.

x.y.z.16

x.y.z.17

x.y.z.158

x.y.z.160

x.y.z.163

x.y.z.164

x.y.z.165

x.y.z.170

x.y.z.175

.

.

.

So, low to high.  In my case, x.y.z is the same first 3 octets, so, no need to sort based on those.  As I bonus, anything that returned the 'highest' IP address would be superb, but I could live with a numerically ascending list.  Using PowerCLI 10.  Thanks! 

KRAEMS

Reply
0 Kudos
4 Replies
LucD
Leadership
Leadership

It feels a bit like cheating, but for IPv4 you can misuse the Version type.

$IPAddresses = @(

'192.168.1.203'

'192.168.1.3'

'192.168.1.17'

'192.168.1.101'

)


$IPAddresses | Sort-Object -Property {[System.Version]$_}


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

Reply
0 Kudos
KRAEMS
Enthusiast
Enthusiast

...I agree that the code snip you shared works, but, it does not seem to work with the collection from my original post - trying yields a lot of:

Sort-Object : Cannot convert value "@{IP Address=x.y.z.99}" to type "System.Version". Error: "Cannot convert the "@{IP Address=x.y.z.99}" value of type

"Selected.VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl" to type "System.Version"."

At line:3 char:11

+ $tester | Sort-Object -Property {[System.Version]$_}

+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidResult: (@{IP Address=x.y.z.99}:PSObject) [Sort-Object], RuntimeException

    + FullyQualifiedErrorId : ExpressionEvaluation,Microsoft.PowerShell.Commands.SortObjectCommand

Reply
0 Kudos
LucD
Leadership
Leadership

That's because you are sorting after the Select-Object, then you don't present simple strings to the Sort-Object cmdlet.

You could do like this.
And I assume you replace 'x.y.z' with real numbers from a subnet

Get-VM | Where-Object {$_.guest.IPAddress[0] -like "x.y.z.*"} |

Sort-Object -Property {[Version]$_.guest.IPAddress[0]} |

Select-Object @{N="IP Address";E={@($_.guest.IPAddress[0])}}


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

Reply
0 Kudos
KRAEMS
Enthusiast
Enthusiast

...works like a charm.  Thanks LucD! 

KRAEMS

Reply
0 Kudos