powershellif-statementwmiout-gridview

Display test-connection successes and failures in Out-Gridview


I am trying to get a list of servers and the last time they rebooted to show in a table. However, if it doesn't respond to a ping, I just need it to show in the list. I can't seem to figure out how to get it to add to the table after else.

Import-CSV $Downtime | % {
if(Test-Connection $_.server -Quiet -count 1){
    Get-WmiObject Win32_OperatingSystem -ComputerName $_.server | 
    select @{LABEL="Name"; EXPRESSION = {$_.PSComputerName}}, @{LABEL="Last Bootup"; EXPRESSION = {$_.convertToDateTime($_.LastBootupTime)}}
    }
else{@{LABEL="Name"; EXPRESSION = {$_.server}}
    }
} | Out-GridView

I can always save the else results in a text file but this would be more convenient.


Solution

  • You need to make the same object, with the same properties!, in both cases so that PowerShell will understand the association between the two. The follwing example builds a custom hashtable using the if/else and outputs the object for each loop pass.

    Import-CSV $Downtime | ForEach-Object {
        $props = @{}
        $server = $_.server
        if(Test-Connection $server -Quiet -count 1){
            $wmi= Get-WmiObject Win32_OperatingSystem -ComputerName $server 
            $props.Name = $wmi.PSComputerName 
            $props."Last Bootup" = $wmi.convertToDateTime($wmi.LastBootupTime)
        }else{
            $props.Name = $server
            $props."Last Bootup" = "Could not contact"
        }
        New-Object -TypeName psobject -Property $props
    } | Out-GridView
    

    I used $server as the $_ changes context a couple of time so we wanted to be able to refer to the current row in the CSV we are processing.

    I don't know what your PowerShell version is so I will assume 2.0 and create objects that support that.

    In both cases an object is created with a Name and Last Bootup property which is populated based on the success of the ping.

    Sample Output

    As an aside I had a similar question a while ago about created similar object based output.