/* ]]> */
Dec 192009
 
Update (8/22/2011): Since you’re looking at ping scripts, you may also be interested in my BackGround Bulk ping script. If you need to quickly ping LOTS of network addresses, then this is the script for you: http://poshtips.com/2011/03/28/bgping-a-high-performance-bulk-ping-utility/

I recently had a need to monitor the stability of a wireless LAN network where we were experiencing some sporadic disconnect issues and decided to cook up this customized ping script.  This “Ping Monitor” script will perform a continuous network ping against a user-specified hostname and provide console output with visual highlighting to draw attention to high response times or time-out situations.  Here are the steps taken in this script:

  • Collect HostName argument from the command line
  • Determine Fully Qualified Domain Name of Hostname
  • Write Heading info and enter into an infinite loop which will Colorize the console output line depending on the ping response time result
    • Infinite Loop:
      • Use get-date to create a formatted timestamp for the ping operation
      • Attempt to PING the specified hostname
      • Use [STRING]::FORMAT to create a formatted string for the results
        • Response Time <= 10ms : use white backround and green foreground
        • Response Time > 10ms : use cyan background and blue foreground
        • Time-Out : use yellow background and red foreground
      • Sleep for 1 second
      • Repeat forever

 

That’s all there is to this one – the script will run indefinitely; to break out of it, simply use CTRL-C from the keyboard

Note: Because the output is generated with the out-host cmdlet (needed for colorizing text) it is not possible to redirect to a log file. A good enhancement would be to collect an optional log-file name from the command line and generate a corresponding CSV listing of the output.  Another would be to add a command-line parameter to set the Response-Time threshold that triggers an output color change.

?Download PingMon.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
$psScriptName = "PingMon.ps1"
$psScriptAuth = "Kahuna at PoshTips.com"
$psScriptDate = "12/19/2009"
##############################################################################
## PingMon.ps1
##
## Original Script by Kahuna at PoshTips.com - 11/19/2009
##
## Maintenance (most recent updates at top):
## Date        By   Comments
## ----------  ---  ----------------------------------------------------------
## 11/19/2009  KPS  new script
##
##############################################################################
$scriptUsage = @"
==============================================================================
 SCRIPT  : $psScriptName
 AUTHOR  : $psScriptAuth
 VERSION : $psScriptDate
==============================================================================
 PURPOSE:
    powershell script to run a coninuous ping against a given host
    and display time-stamped response times to the console with
    color highlighting for high response times or time-outs
 
 USAGE:
 
    PingMon hostname [-?|-H]
 
    - From the PowerShell command-line, invoke the script, passing a single
      hostnames argument
  FLAGS:
    -? or -H  = Display this help
 
  EXAMPLE:
              ./PingMon server1
 
==============================================================================
"@
 
Set-PSDebug -Trace 0
$script:recCount = 0
 
function ShowUsage([string]$message=""){
    $message
    $scriptUsage
    exit
    }
 
function DoPing ([string]$hostname){
    #$erroractionpreference = "SilentlyContinue"
    $hostname = $hostname.trimend(".")
 
    $fqdn = [System.Net.Dns]::GetHostEntry($hostname).HostName
 
    write-host "Date                 Status  ResponseTime   Host (IP)" -foregroundcolor cyan -backgroundcolor darkblue
    write-host "-------------------  ------  -------------  ------------------------------------" -foregroundcolor cyan -backgroundcolor darkblue
    #          "YYYY-MM-DD_HH:MM:SS  OK      9999999ms      Host (xxx.xxx.xxx.xxx)"
    #          "YYYY-MM-DD_HH:MM:SS  FAIL    TIMEOUT        Host (xxx.xxx.xxx.xxx)"
 
    $ping = new-object System.Net.NetworkInformation.Ping
    while(-1) {
 
        $ts = get-date -uformat %Y-%m-%d_%H:%M:%S
        $reply = $ping.send($hostname)
        if ($reply.status -eq "Success"){
            $x = [string]::Format("{0}  {1}  {2,7:D}ms      {3} ({4})",
                $ts,
                "OK    ",
                $reply.RoundtripTime,
                $fqdn,
                $reply.Address.ToString())
 
        if ($reply.RoundtripTime -le 10) {
            write-host $x -foregroundcolor darkgreen -backgroundcolor white
            }
        else {
            write-host $x -foregroundcolor Blue -backgroundcolor cyan
            }
        }
    else {
            $x = [string]::Format("{0}  {1}  {2}        {3} ({4})",
                $ts,
                "FAIL  ",
                "TIMEOUT",
                $fqdn,
                "")
            write-host $x -foregroundcolor red -backgroundcolor yellow
            }
        sleep 1
        }
    }
 
######################################################
## MAIN
######################################################
if ($args.count)
    {
    # Process command-line flags
    foreach ($item in $args)
        {
        if ($item -like "-*")
            {
            switch ($item)
                {
                "-H" {ShowUsage;}
                "-?" {ShowUsage;}
                default {ShowUsage "ERROR: $item is invalid!";}
                }
            }
        }
    # Process non-flag arguments
    foreach ($item in $args) {
        if ($item -notlike "-*") {
            DoPing $item
            }
        }
    }
else
    {
    ShowUsage "ERROR: This script requires arguments"
    }

 Posted by at 5:21 pm

  3 Responses to “PingMon – A PowerShell Ping Monitor Script”

  1. Hi,

    Great script! I only have one problem & maybe you can help me out. If i create a function of hte script like:

    Function ping {C:\PingMon.ps1}

    & i use in powershell:
    ping server01

    i get the response:

    ERROR: This script requires arguments

    so i guess i have to put something behind c:\pingmon.ps1 like

    Function ping {C:\PingMon.ps1 captureinput}

    but dunno how (i’m a n00b :P ).

    does anyone know?

  2. Hi Wes,

    If you want to use this within another script, just rip out the existing “DoPing” function and put it in your script. You can then call the “DoPing” function like this:

    DoPing server01

    if you want to call this script from another script, don’t try to turn it into a function, just invoke it from within your script as you would from the PowerShell commandline:

    ./pingmon.ps1 server01

  3. Nice script.

    I had the problem, that the output can’t be used with the | Out-File — command, so I added the parameter -e for output with the echo-command:


    $psScriptName = "PingMon.ps1"
    $psScriptAuth = "Kahuna at PoshTips.com"
    $psScriptDate = "12/19/2009"
    ##############################################################################
    ## PingMon.ps1
    ##
    ## Original Script by Kahuna at PoshTips.com - 11/19/2009
    ##
    ## Maintenance (most recent updates at top):
    ## Date By Comments
    ## ---------- --- ----------------------------------------------------------
    ## 11/19/2009 KPS new script
    ## 06/10/2011 LS add parameter -e
    ##
    ##############################################################################
    $scriptUsage = @"
    ==============================================================================
    SCRIPT : $psScriptName
    AUTHOR : $psScriptAuth
    VERSION : $psScriptDate
    ==============================================================================
    PURPOSE:
    powershell script to run a coninuous ping against a given host
    and display time-stamped response times to the console with
    color highlighting for high response times or time-outs

    USAGE:

    PingMon [-e] hostname [-?|-H]

    - From the PowerShell command-line, invoke the script, passing a single
    hostnames argument
    FLAGS:
    -? or -H = Display this help
    -e = Return in echo-commands (for Out-File - Command), not coloured.

    EXAMPLE:
    ./PingMon server1

    ==============================================================================
    "@

    Set-PSDebug -Trace 0
    $script:recCount = 0

    function ShowUsage([string]$message=""){
    $message
    $scriptUsage
    exit
    }

    function DoPing ([string]$hostname,[bool]$echo){
    #$erroractionpreference = "SilentlyContinue"
    $hostname = $hostname.trimend(".")
    $fqdn = [System.Net.Dns]::GetHostEntry($hostname).HostName

    if ($echo)
    {
    echo "Date Status ResponseTime Host (IP)"
    echo "------------------- ------ ------------- ------------------------------------"
    }
    else {
    write-host "Date Status ResponseTime Host (IP)" -foregroundcolor cyan -backgroundcolor darkblue
    write-host "------------------- ------ ------------- ------------------------------------" -foregroundcolor cyan -backgroundcolor darkblue
    # "YYYY-MM-DD_HH:MM:SS OK 9999999ms Host (xxx.xxx.xxx.xxx)"
    # "YYYY-MM-DD_HH:MM:SS FAIL TIMEOUT Host (xxx.xxx.xxx.xxx)"
    }

    $ping = new-object System.Net.NetworkInformation.Ping
    while(-1) {

    $ts = get-date -uformat %Y-%m-%d_%H:%M:%S
    $reply = $ping.send($hostname)
    if ($reply.status -eq "Success"){
    $x = [string]::Format("{0} {1} {2,7:D}ms {3} ({4})",
    $ts,
    "OK ",
    $reply.RoundtripTime,
    $fqdn,
    $reply.Address.ToString())

    if ($echo)
    { echo $x }
    else
    {
    if ($reply.RoundtripTime -le 10) {
    write-host $x -foregroundcolor darkgreen -backgroundcolor white
    }
    else {
    write-host $x -foregroundcolor Blue -backgroundcolor cyan
    }
    }
    }
    else {
    $x = [string]::Format("{0} {1} {2} {3} ({4})",
    $ts,
    "FAIL ",
    "TIMEOUT",
    $fqdn,
    "")

    if ($echo)
    { echo $x }
    else
    { write-host $x -foregroundcolor red -backgroundcolor yellow }
    }
    sleep 1
    }
    }

    ######################################################
    ## MAIN
    ######################################################
    if ($args.count)
    {
    [bool]$echo = $False
    # Process command-line flags
    foreach ($item in $args)
    {
    if ($item -like "-*")
    {
    switch ($item)
    {
    "-H" {ShowUsage;}
    "-?" {ShowUsage;}
    "-e" {$echo = $True;}
    default {ShowUsage "ERROR: $item is invalid!";}
    }
    }
    }
    # Process non-flag arguments
    foreach ($item in $args) {
    if ($item -notlike "-*") {
    DoPing $item $echo
    }
    }
    }
    else
    {
    ShowUsage "ERROR: This script requires arguments"
    }

    Example to use:

    .\PingMon.ps1 -e xxx.xxx.xxx.xxx | Out-File your-log-output.log

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Page optimized by WP Minify WordPress Plugin