powershellparallel-processingicmp

Append to array in powershell job


I was able to find a piece of code that could ping all systems at once, better than any other job examples I've come across. This thing can take an entire file full of hosts, line by line, and ping them all literally at the same time. But how can I add the ones that are up to my $online array? I tried adding in the true block but it didn't work. Im simply trying to stick $online += $pc somewhere. Any help would be appreciated. Thanks.

$online = @()
$pc = Get-Content C:\servers.txt 
$pc | ForEach-Object { Test-Connection -ComputerName $_ -Count 1 -AsJob } | Get-Job | Receive-Job -Wait | Select-Object @{Name='ComputerName';Expression={$_.Address}},@{Name='Reachable';Expression={if ($_.StatusCode -eq 0) { $true } else { $false }}} | ft -AutoSize

Solution

  • I believe the issue here is the pipe ft -autosize.

    Try to pipe after the if/else statement as per below:

    | ForEach-Object {
        if ($_.Reachable -eq $true) {
            $online += $_.ComputerName
        }
    }
    

    Then if you want to view the results you can always do:

    $online | ft -AutoSize
    

    I'd also suggest a better formatting as all one line isn't easy to read. Try something like this:

    $online = @()
    $pc = Get-Content C:\servers.txt 
    $pc | ForEach-Object { 
        Test-Connection -ComputerName $_ -Count 1 -AsJob 
    } | Get-Job | Receive-Job -Wait | 
    Select-Object @{Name='ComputerName';Expression={$_.Address}},@{Name='Reachable';Expression={
        if ($_.StatusCode -eq 0) { 
            $true 
        } else { 
            $false 
        }
    }} | ForEach-Object {
        if ($_.Reachable -eq $true) {
            $online += $_.ComputerName
        }
    }
    $online | ft -AutoSize