0

So im pretty new to powershell and i have multiple questions on how to write scripts using it but right now my main issue is that i want to be able to ping all of the computers on my network and take the names of the computers that ping back and put them into an array so that i can push updates to the computers that are on the network just using one array containing the current computers on the network. here is what i am working with right now.

foreach ($c in $204computernames) 
{if(test-connection -computername $c.name  -count 1 -quiet)
{write-host $c.name
}
}

currently this string of code runs a foreach loop so that $c(the computers) run against $204computernames(the known computers on the network)then it tests the positive connections through the if statement and finally at the end it outputs the names of the computers that are on the network. Now the problem im understanding from this is when i use a foreach loop that it will run against all of the known computers and as each computer is put through the loop it is replaced by the preceding one, but i want each and every one that comes back on the network to be stored in an array. Is there a way that i can do this with the current format or is there a certain way that i can tweak what i have so that i can get the output i want?

3
  • this is my first post as well so im sorry if its confusing Commented Jun 16, 2020 at 14:48
  • 1
    Is $computernames.name (as an argument to Test-Connection) a typo? Commented Jun 16, 2020 at 14:59
  • it was a typo, i corrected the code, iv been working with alot of variations to get it to work the way i want it to Commented Jun 16, 2020 at 15:15

1 Answer 1

1

The idiomatic solution to "how do I filter a list against a condition and save the results" would be to pipe the input to Where-Object:

$onlineComputers = $204computernames |Where-Object { Test-Connection $_.name -Count 1 -Quiet }
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much for this answer, it worked exactly how i wanted it to!
@Zizzay That's great to hear, you're most welcome! Please consider marking the answer "accepted" by clicking the checkmark on the left :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.