Monitoring a PING connection with PowerShell

16. April 2015

This script will let you silently monitor a PING connection to 3 hosts. We apply this via GPO as a login script and it will monitor the user’s connection to those hosts and write connection losses to the outfile shown in line 4.

If a connection loss to one of the main hosts occurs we added 2 subhosts to check and see if the connection to the local gateway and filesever is OK.

$ErrorActionPreference= 'silentlycontinue'
$date_header = Get-Date -Format ddMMyy

$outfile = "PATHTOYOURLOG_$($env:USERNAME)_$($env:COMPUTERNAME)_$($date_header).log"
$host1 = "YOURHOST"
$host2 = "YOURHOST"
$host3 = "YOURHOST"
$sub_host1 = "YOURSUBHOST"
$sub_host2 = "YOURSUBHOST"
Get-Date -Format "dd.MM.yy HH:mm:ss" | Out-File $outfile -Append
echo "Starting script..." | Out-File $outfile -Append

        do
        {
        
        # HOST1
        Test-Connection $host1 -Count 4 | out-null
        if ([int]$? -eq 0)
            {
            $date = Get-Date -Format "HH:mm:ss"
            echo "########################################################" | Out-File $outfile -Append
            echo "$date Lost connection to $host1" | Out-File $outfile -Append
            # SUB-HOST1
            Test-Connection $sub_host1 -Count 1 | Out-File $outfile -Append
            # SUB-HOST2
            Test-Connection $sub_host2 -Count 1 | Out-File $outfile -Append
            }

        # HOST2
        Test-Connection $host2 -Count 4 | out-null
        if ([int]$? -eq 0)
            {
            $date = Get-Date -Format "HH:mm:ss"
            echo "########################################################" | Out-File $outfile -Append
            echo "$date Lost connection to Host $host2" | Out-File $outfile -Append
            # SUB-HOST1
            Test-Connection $sub_host1 -Count 1 | Out-File $outfile -Append
            # SUB-HOST2
            Test-Connection $sub_host2 -Count 1 | Out-File $outfile -Append
            }

        # HOST3
        Test-Connection $host3 -Count 4 | out-null
        if ([int]$? -eq 0)
            {
            $date = Get-Date -Format "HH:mm:ss"
            echo "########################################################" | Out-File $outfile -Append
            echo "$date Lost connection to $host3" | Out-File $outfile -Append
            # SUB-HOST1
            Test-Connection $sub_host1 -Count 1 | Out-File $outfile -Append
            # SUB-HOST2
            Test-Connection $sub_host2 -Count 1 | Out-File $outfile -Append
            }

        }
        while ($asd = 1)

PowerShell Version: 4
Modules: none

#PowerShell

Leave a Reply

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


*