Powershell - Testing ports on multiple servers

nico-
nico- used Ask the Experts™
on
Hello

I'm looking to use Test-NetConnectivity to check for port 53 but instead of checking one server, I'm hoping to use a script that would import a CSV (with the server ip addresses) and then check port 53 for all servers in the file .. and then output clear results to a separate file.  I'm not sure how to avoid the ping that seems to be a part of the cmdlet.

Hope you can help
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2018

Commented:
If you have a textfile with servers one in each line,
the command would be
gc D:\list.txt |test-NetConnection -port 53

Open in new window

Top Expert 2015

Commented:
Here ya go,

The input CSV needs a column called IPAddress.

Also generates a nice report to CSV file at end for you.

$Port = 53
$Report = @()
$Servers = Import-CSV c:\folder\filename.csv
Foreach ($Server in $Servers) {
		$Alive = Test-NetConnection -Port $port -ComputerName $Server.IPAddress | Select TcpTestSucceeded
		IF ($Alive.TcpTestSucceeded -eq "True") {
			$TestResult = New-Object psobject -Property @{
				IPAddress = $Server.IPAddress
				Result = "Port " + $Port + " is OPEN"
			}
		}
		ELSE {
			$TestResult = New-Object psobject -Prop @{
				IPAddress = $Server.IPAddress
				Result = "Port " + $Port + " is CLOSED"
			}
		}
		$Report += $TestResult
}		
$Report | select IPAddress, Result | Export-Csv c:\Folder\Report.csv -nti

Open in new window

Author

Commented:
Hello

Very close.  I'm testing 2 servers where I can connect to one but not the other (tested using telnet and test-netconnection.

Your report has both the result of both being closed

Can you re-check

thank you
Top Expert 2015
Commented:
Hi Nico,

I updated the script a little after posting it, as I left out the Array Value from the IF statement.
I've just retested the script above on 3 of my servers and I received and Open, Closed, Open result as expected.

You may have copied it before I updated the script so could you give it another go please?

Author

Commented:
Absolutely superb.  Shame it's worth only 500 points!  I couldn't find that anywhere on the Internet and then remembered I had an account on hrere!

thanks for you help.  much appreciated.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial