PowerShell Tip of the Week: Check connectivity to multiple servers

You can find multiple articles on our blog about checking connectivity. This time I want to show you how to check it for bunch of servers on specific port.

Check connectivity

Script will use Test-NetConnection command where you can specify port number. For single machine you can use the following one-liner script:

$Server = "DC01"
$DServer = "SCOM01"
$Port = "5723"
Invoke-Command  -ComputerName $Server -ScriptBlock{param($Port,$DServer) Test-netconnection -Port $Port -cn $DServer -InformationLevel Quiet } -ArgumentList $Port,$DServer

On the beginning you have to provide servers and destination servers againts which you want to check connection:


    $Servers = Get-Content -Path "d:\scripts\servers.txt"
    $DestinationServ = "SCOM01","SCOM02","SCOM03","SCOMO4","SCOM05","SCOM06"

At the end output should look like this:

Check connectivity
Check connectivity

Final script:


    $Servers = Get-Content -Path "d:\scripts\servers.txt"
    $DestinationServ = "SCOM01","SCOM02","SCOM03","SCOMO4","SCOM05","SCOM06"
    $Array = @()
    $Port = "5723"

    Foreach($Server in $Servers)
    {
        $Obejct = $null
        $FQDN = $null
        $Server = $Server.Trim()

        Write-Host Processing $Server -ForegroundColor Green
        
        #Check FQDN for remote computer 
        $FQDN = ([System.Net.Dns]::GetHostByName(("$Server")))

        If(!$FQDN)
        {
            Write-Host "$Server does not exist"
        }
        Else
        {
            # Create a custom object 
            $Object = New-Object PSCustomObject
            $Object | Add-Member -MemberType NoteProperty -Name "Server name" -Value $server
            $Object | Add-Member -MemberType NoteProperty -Name "Port" -Value $Port

            Foreach($DServer in $DestinationServ)
            {
                $Test = $null
                Try
                {
                    $Test = Invoke-Command  -ComputerName $Server -ErrorAction Stop -ScriptBlock{param($Port,$DServer) Test-netconnection -Port $Port -cn $DServer -InformationLevel Quiet } -ArgumentList $Port,$DServer
                    If($Test)
                    {
                        $Object | Add-Member -MemberType NoteProperty -Name "$DServer" -Value $Test
                    }
                }
                Catch
                {
                    Write-Warning $_.Exception.Message
                    $Object | Add-Member -MemberType NoteProperty -Name "$DServer" -Value "null"
                }
            }
            $Array += $Object   

        }
    }
    Write-Host "Results:" -Foreground Yellow
    $Array | Format-Table -Wrap -AutoSize
    $Array | Export-Csv -Path d:\scripts\results.csv -NoTypeInformation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.