$servers = @{
'google.com' = (80,8080)
'gmail.com' = 443
'google.it' = 8080
}
$ProgressPreference = 'SilentlyContinue'
$servers.keys | ForEach-Object {
$site = $_
$servers[$_] | ForEach-Object {
"Testing {0} - {1}" -f $_, $site
Test-NetConnection $site -Port $_
}
}
Powershell to check different ports on different servers
Andrea.me
21
Reputation points
Good Day All,
I am powershell noob and can't figure out how to make this code working
$servers = @{
'google.com' = (80,8080)
'gmail.com' = 443
'google.it' = 8080
}
$ProgressPreference = 'SilentlyContinue'
$servers.Keys |
ForEach-Object{
Test-NetConnection -ComputerName $_ -Port $servers[$_]
}
If I make 2 rows for "google.com" it do not work, I should have a loop for each port, but I cannot figure how.
Any suggestion?
Thank you and best regards
Windows for business | Windows Server | User experience | PowerShell
8,330 questions
Accepted answer
-
MotoX80 36,401 Reputation points
2021-02-11T19:16:14.067+00:00
2 additional answers
Sort by: Most helpful
-
Andreas Baumgarten 123.6K Reputation points MVP Volunteer Moderator
2021-02-11T18:30:25.89+00:00 Maybe this is helpful:
$servers = @( [pscustomobject]@{ServerName='google.com';Port='80'} [pscustomobject]@{ServerName='google.com';Port='8080'} [pscustomobject]@{ServerName='gmail.com';Port='443'} [pscustomobject]@{ServerName='google.it';Port='80'} ) foreach ($server in $servers) { $ServerName = $server.ServerName $Port = $server.Port Write-Output "Testing $Port on $ServerName" Test-Connection $ServerName -TcpPort $Port }
----------
(If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)
Regards
Andreas Baumgarten -
Rich Matheisen 47,901 Reputation points
2021-02-11T19:50:41.18+00:00 Slightly longer than the other suggestions:
$servers = [ordered]@{ 'google.com' = 80, 8080 'gmail.com' = 443 'google.it' = 8080 } $servers.GetEnumerator() | ForEach-Object { # for each host $server = $_.Key $port = "" $_.Value | ForEach-Object { # for each port $port = $_ Try { $tcp = (New-Object System.Net.Sockets.TcpClient).Connect($host, $_) [PSCustomObject]@{ Host = $server Port = $_ OK = $true } } Catch { [PSCustomObject]@{ Host = $server Port = $port OK = $false } } } }