{"id":89,"date":"2019-06-30T13:37:20","date_gmt":"2019-06-30T12:37:20","guid":{"rendered":"http:\/\/192.168.8.14\/?p=89"},"modified":"2019-07-06T21:21:11","modified_gmt":"2019-07-06T20:21:11","slug":"powershell-ping-function","status":"publish","type":"post","link":"https:\/\/www.jasonstreet.com\/?p=89","title":{"rendered":"My Powershell Ping function"},"content":{"rendered":"\n<p>This is a nicer looking (than) Ping function I wrote in Powershell a while ago. <br>It&#8217;s a simple Ping function that only writes a new line when there is a state change. So the output is much neater then a ping -t command that rapidly scrolls off the screen.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"680\" height=\"69\" src=\"http:\/\/192.168.8.14\/wp-content\/uploads\/2019\/06\/output001.jpg\" alt=\"\" class=\"wp-image-90\" srcset=\"https:\/\/www.jasonstreet.com\/wp-content\/uploads\/2019\/06\/output001.jpg 680w, https:\/\/www.jasonstreet.com\/wp-content\/uploads\/2019\/06\/output001-300x30.jpg 300w\" sizes=\"auto, (max-width: 680px) 100vw, 680px\" \/><figcaption> In the example above the last line is over written on each ping until there is a state change. <\/figcaption><\/figure>\n\n\n\n<p>The function will take the following parameters<\/p>\n\n\n\n<p>JPing [-Target] &lt;string&gt; [-Count &lt;int&gt;] [-StateChanes &lt;int&gt;] [TimeInt &lt;int&gt;] [LogFile &lt;string&gt;]<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Target (mandatory) the IP or FQDN of the target <\/li><li>TimeInt (optional) The delay in seconds between each ping (default 1)<\/li><li>Count (optional) exit after specific number of pings (default infinite) <\/li><li>StateChanges (optional) exit after specific number of statechanges (default infinite) <\/li><li>LogFile (optional) path to log file <\/li><\/ul>\n\n\n\n<p> <\/p>\n\n\n\n<p>Any switches can be used. If the LogFile path cannot be written to, the function displays an error, disable file logging and continue.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: powershell; title: ; notranslate\" title=\"\">\nfunction JPing {\n  Param (\n  &#x5B;Parameter(Mandatory=$true)] &#x5B;string]$Target,\n  &#x5B;Parameter(Mandatory=$false, ValueFromPipeline=$False)] &#x5B;int]$TimeInt = 1,        # time between pings in seconds (note a failed ping has to time out so the int will be longer for connection failures)\n  &#x5B;Parameter(Mandatory=$false, ValueFromPipeline=$False)] &#x5B;int]$Count = 0,          # number of pings before scipt ends. 0 = infinate\n  &#x5B;Parameter(Mandatory=$false, ValueFromPipeline=$False)] &#x5B;int]$StatChanges = -1,    # number of state changes before script will end.\n  &#x5B;Parameter(Mandatory=$false, ValueFromPipeline=$False)] &#x5B;string]$LogFile = &quot;DoNotLog&quot;\n  )\n\n  if ($logFile -eq &quot;DoNotLog&quot;)\n  {\n    # LogFile is not set\n    $LogToFile = $false\n  }else{\n    # logfile set. write a header line and then test the files exists\n    $LogToFile = $true\n    $Time = (get-date -f &quot;yyyyMMdd HH:mm:ss&quot;).ToString()\n    # write header line to log file. if path does not exist catch the error and disable file logging.\n    try\n    {\n      &quot;Testing Connection to $Target at $Time&quot; | out-file $LogFile -ErrorAction SilentlyContinue\n    }\n    catch\n    {\n      $LogToFile = $false\n      write-host &quot;Error unable to write to $LogFile. Logfile disabled&quot; -ForegroundColor Red\n    }\n  }\n\n  $FirstRun = $True\n  $LastState = &quot;Unknown&quot;\n  $CurrentState = &quot;Unknown&quot;\n  $NumPings = 0\n  $NumStatChanges = 0\n  $origpos = $host.UI.RawUI.CursorPosition\n  do{\n    $NumPings ++    \n\n    # get the current time and ping the target\n    $Time = (get-date -f &quot;yyyyMMdd HH:mm:ss&quot;).ToString()\n    $bob = test-connection -ComputerName $Target -Count 1 -ErrorAction SilentlyContinue\n    if ($?)\n    {\n      # Ping responds, target is up\n      $RTime = $bob.ResponseTime\n      $CurrentState = &quot;Up&quot;\n\n      # check if this is the frist ping. if it is then set the LastState to the CurrentState so we dont get a state change and write a header first ping line\n      if ($FirstRun)\n      {\n        $LastState = $CurrentState\n        write-host &quot;$Time `t $Target is up. response time $RTime ms (first ping)     &quot; -ForegroundColor Green\n        $origpos = $host.UI.RawUI.CursorPosition\n\n        # if logging is enabled, write to log file\n        if ($LogToFile) {&quot;$Time `t $Target is up. response time $RTime ms (first ping)&quot; | out-file $LogFile -Append}\n        $FirstRun = $false\n      }\n\n      # check if the current state of the target is the same as the last state \n      if ($CurrentState -eq $LastState)\n      {\n        # no state change\n        $host.UI.RawUI.CursorPosition = $origpos\n        write-host &quot;$Time `t $Target is up. response time $RTime ms ($NumPings)     &quot; -ForegroundColor Green\n      }else{\n        # state change. target is now up from down or unknown state\n        $host.UI.RawUI.CursorPosition = $origpos\n        write-host &quot;$Time `t $Target is now up. response time $RTime ms ($NumPings)    &quot; -ForegroundColor Green\n        $origpos = $host.UI.RawUI.CursorPosition\n\n        # if logging is enabled, write to log file\n        if ($LogToFile) {&quot;$Time `t $Target is now up. response time $RTime ms ($NumPings)&quot; | out-file $LogFile -Append}\n        $NumStatChanges ++\n      }\n      $LastState = &quot;Up&quot;\n    }else{\n      #Ping does not respond.  target is down\n      $CurrentState = &quot;Down&quot;\n\n      # check if this is the frist ping. if it is then set the LastState to the CurrentState so we dont get a state change and write a header first ping line\n      if ($FirstRun)\n      {\n        $LastState = $CurrentState\n        write-host &quot;$Time `t $Target is Down. (first ping)                        &quot; -ForegroundColor red\n        $origpos = $host.UI.RawUI.CursorPosition\n\n        # if logging is enabled, write to log file\n        if ($LogToFile) { &quot;$Time `t $Target is Down. (first ping)&quot; | out-file $LogFile -Append}\n        $FirstRun = $false\n      }\n\n      # check if the current state of the target is the same as the last state\n      if ($CurrentState -eq $LastState)\n      {\n        # no state change\n        $host.UI.RawUI.CursorPosition = $origpos\n        write-host &quot;$Time `t $Target is Down. ($NumPings)                        &quot; -ForegroundColor red\n      }else{\n        # state change. target is now down from up or unknown state\n        $host.UI.RawUI.CursorPosition = $origpos\n        write-host &quot;$Time `t $Target is now Down. ($NumPings)                     &quot; -ForegroundColor red\n        $origpos = $host.UI.RawUI.CursorPosition\n\n        # if logging is enabled, write to log file\n        if ($LogToFile) {&quot;$Time `t $Target is now Down. ($NumPings)&quot; | out-file $LogFile -Append}\n        $NumStatChanges ++\n\n      }\n      $LastState = &quot;Down&quot;\n    }\n\n    start-sleep -Seconds $TimeInt\n    $FirstRun = $false\n\n  }until ($Count -eq $NumPings -or $StatChanges -eq $NumStatChanges)\n}\n\n<\/pre><\/div>","protected":false},"excerpt":{"rendered":"<p>This is a nicer looking (than) Ping function I wrote in Powershell a while ago. It&#8217;s a simple Ping function that only writes a new line when there is a state change. So the output is much neater then a ping -t command that rapidly scrolls off the screen. The function will take the following&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[4],"tags":[17,16,13],"class_list":["post-89","post","type-post","status-publish","format-standard","hentry","category-powershell","tag-function","tag-ping","tag-powershell"],"_links":{"self":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/posts\/89","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=89"}],"version-history":[{"count":0,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/posts\/89\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=89"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=89"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=89"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}