Automation

 View Only
  • 1.  Sorting IP addresses

    Posted May 04, 2018 05:58 PM

    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



  • 2.  RE: Sorting IP addresses

    Posted May 04, 2018 06:22 PM

    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]$_}



  • 3.  RE: Sorting IP addresses

    Posted May 04, 2018 06:42 PM

    ...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



  • 4.  RE: Sorting IP addresses

    Posted May 04, 2018 06:56 PM

    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])}}



  • 5.  RE: Sorting IP addresses

    Posted May 07, 2018 03:27 PM

    ...works like a charm.  Thanks LucD! 

    KRAEMS