Search code examples
powershellserveripnew-operatorping

New to PowerShell, trying to find something that gives this output for a list of IPs


Like the title says i'm super new in PowerShell and i was trying to get the ping to a list of different IP's and servers at work.

I found this script on here and it kinda gives what i want (i touched a little bit):

$group = @()
    foreach ($ip in $Iplist) {
    $status = @{ "Servidor" = $ip; "Fecha" = (Get-Date -Format "dd/MM/yyyy HH:mm") }
$pings = Test-Connection $ip
    if ($pings) {
        $status["AverageResponseTime"] =
            ($pings | Measure-Object -Property ResponseTime -Average).Average
    $status["Estado"] = "OK"
}
    else {
        $status["Estado"] = "Down"
}

        New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
        $group += $serverStatus

}

The output to this one is this:

Estado Fecha            AverageResponseTime Servidor
------ -----            ------------------- --------
OK     03/09/2021 22:58                5.25 IP 1
OK     03/09/2021 22:58               33.75 IP 2
OK     03/09/2021 22:58                 5.5 IP 3

But i wanted to get an output like this:

------   --------        -------------------    ---   ---  --------
IP1     03/09/2021 22:58                5.25    4ms   6ms      OK
IP2     03/09/2021 22:58               33.75    25ms  40ms     OK    
IP3     03/09/2021 22:58                 5.5    4ms   6ms      OK

And honestly i dont know how to get it like that. If anyone has any advice/line i'll greatly appreciate it.


Solution

  • Ordered Hash Tables

    This is due to how PowerShell doesn't enforce ordering of keys for hash-tables. More information here: https://devblogs.microsoft.com/scripting/use-powershell-to-create-ordered-dictionary/

    To amend your code such that it will enforce the order, change this line, adding the ordered attribute tag:

    $status = [ordered]@{ "Servidor" = $ip; "Fecha" = (Get-Date -Format "dd/MM/yyyy HH:mm") }
    

    This means your keys will be in the order you specify. When new keys are added they are kept at the end of the hashtable. Your final keys before creating the output object will be:

    1. Servidor
    2. Fecha
    3. AverageResponseTime
    4. Estado

    Which I think is what you want.

    Select-Object

    Another way of enforcing an order, just for display purposes is the Select-Object cmdlet. For example in your case, you can print the data in the order of choice by listing named Properties in order:

    $group | Select-Object Servidor, Fecha, AverageResponseTime, Estado
    

    Piping again to something like Export-Csv would create an output file with keys in the order specified.