Troy Hector
Troy Hector

Reputation: 25

Output if/else statement results to formatted table

I have written an environment IP check script in Powershell which works but I can't figure out how to display the output to screen in a formatted table which auto sizes the columns.

$infile = Import-Csv "~\Env_IPlist.csv" -Delimiter ","
$arr1 = @()

$IP_Addresses = $infile |
                Select-Object "Device_Type", "Device_Name", "IP_Address",
                    "IP_Role", "Location"

Write-Host "Started Ping Test ..."

foreach ($IP in $IP_Addresses) {
    if (Test-Connection $IP.("IP_Address") -Quiet -Count 1 -ErrorAction SilentlyContinue) {
        Write-Host $IP.("Device_Name") ":" $IP.("IP_Address") "Ping successful" -ForegroundColor Green
    } else {
        Write-Host $IP."Device_Name" ":" $IP.("IP_Address") "Ping failed" -ForegroundColor Red -BackgroundColor white
    }
}

Write-Host "Ping Test Completed!"

Upvotes: 2

Views: 472

Answers (2)

Troy Hector
Troy Hector

Reputation: 25

I rewrote the script using PSObject as initially suggested but now I do not know how to add the ForegroundColor in the if..else statement.

$infile = Import-Csv "~\Env_IPlist.csv" -Delimiter ","
$arr1 = @()

$IP_Addresses = $infile |
                Select-Object Device_Type, Device_Name, IP_Address, IP_Role,
                    Location, Status

foreach ($IP in $IP_Addresses) {
    if (Test-Connection $IP.IP_Address -Quiet -Count 1 -ErrorAction SilentlyContinue) {
        $PSObject = New-Object PSObject -Property @{
            Device_Type = $IP.Device_Type
            Device_Name = $IP.Device_Name
            IP_Address  = $IP.IP_Address
            IP_Role     = $IP.IP_Role
            Location    = $IP.Location
            Status      = "Successful"
        }
    } else {
        $PSObject = New-Object PSObject -Property @{
            Device_Type = $IP.Device_Type
            Device_Name = $IP.Device_Name
            IP_Address  = $IP.IP_Address
            IP_Role     = $IP.IP_Role
            Location    = $IP.Location
            Status      = "Failed"
        }
    }
    $arr1 += $PSObject
}

$arr1 | Format-Table -AutoSize

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

Add the Test-Connection result via a calculated property, then pipe the output to Format-Table.

$infile |
    Select-Object Device_Type, Device_Name, IP_Address, IP_Role, Location,
        @{n='Online';e={
            [bool](Test-Connection $_.IP_Address -Quiet -Count 1 -EA SilentlyContinue)
        }} |
    Format-Table -AutoSize

Upvotes: 2

Related Questions