Create a variable for online and offline computers using test-connection

I am using the below script to capture the online and offline computers into different variables but I am getting only one computer name in each variable. What am I doing wrong. Can some one help please. I am new to powershell. Thanks.
Script:
$NOLaps | ForEach-Object {
if (test-connection -computername $_ -quiet -count 1) {
new-object psobject -property @{ComputerName=$} | Select-Object -ExpandProperty ComputerName -OutVariable Online
}
else {
new-object psobject -property @{ComputerName=$
} | Select-Object -ExpandProperty ComputerName -OutVariable Offline
}
}

I’d recommend a little more streamlined approach … like this:

$ConnectionStatusList =
foreach ($ComputerName in $NOLaps) {
    [PSCustomObject]@{
        ComputerName = $ComputerName
        Online       = Test-Connection -ComputerName $ComputerName -Count 1 -Quiet
    }
}
$ConnectionStatusList

And BTW: When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org 1 <---- Click :point_up_2:t4: :wink:

( !! Sometimes the preformatted text button hides behind the settings gear symbol. :wink: )

Hi Olaf. Here is the code in right format. My objective is to get all the online computers in one variable and offline computers in another variable. I am not getting any error but the variables are capturing only the last computer and skipping others. Trying to work out to get all the computers in the variables. I am not getting any error though. I can see the list of computers on the screen but the “Online” variable has only one computer object and it is the same case with “Offline” variable. Your help is appreciated.

$NOLaps | ForEach-Object {
if (test-connection -computername $_ -quiet -count 1) {
    new-object psobject -property @{ComputerName=$_} | Select-Object -ExpandProperty ComputerName -OutVariable Online
    }
else {
new-object psobject -property @{ComputerName=$_} | Select-Object -ExpandProperty ComputerName -OutVariable Offline
}
}

???
:man_shrugging:t3: :man_shrugging:t3:

Have you actually read my reply? Have you tried my code suggestion? If not - why not?

Why two separate variables? Why not one array containing all information you need? Try my suggestion.

Edit:

Let me guess … it’s always the last computer tested for both variables, right? :smirk:

You are overwriting the variables with each loop iteration. :man_shrugging:t3:

Change -OutVariable Online to -OutVariable +Online

The + appends to the variable

Thanks for you help krzydoug.