Test-Connection

We’ve looked at test-connection before – the PowerShell ping

"192.168.196.142", "192.168.196.1" | foreach {Test-Connection -ComputerName $_}

will return the IPv4 and IPv6 addresses and the time taken for the ping among other information

if we want to test a lot of machines – put the addresses (or names) into a csv file

Computer
"192.168.196.142"
"192.168.196.1"

import-csv test.csv | foreach {Test-Connection -ComputerName $_.computer}

next step is to output the results.  say we want a list of computers that we can contact

import-csv test.csv | foreach {if (Test-Connection -ComputerName $_.computer -Quiet){Add-Content -value $_.Computer -path computers.txt}}

The –Quiet parameter changes the output so we get a boolean (true or false) – we can ping it or we can’t

This could be changed to a list that didn’t respond by changing the test in the if statement.

If we have a lot of machines to test then we need to make it a job

start-job -Name j1 -ScriptBlock {import-csv c:scriptstest.csv | foreach {if (Test-Connection -ComputerName $_.computer -Quiet){Add-Content -value $_.Computer -path c:scriptscomputers.txt}}}

Receive-Job won’t return anything for this job as the output is all in the file.  Note that we have to give the full path to the files as the job assumes you are working in your user documents folder

A simple little script to test the machines on the network.  Next we have to consider how we can build up the lit of machines.

About these ads
This entry was posted in PowerShell V2. Bookmark the permalink.

2 Responses to Test-Connection

  1. Dmitry says:

    This foreach looks quite ugly here. Just piping addresses into Test-Connection would have looked way prettier…

  2. Richard says:

    It does look ugly – but test-connection does not work nicely with the pipeline

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s