Monday, April 23, 2018

When did these Pings run?

Greetings.

Took a little break from the blog.  I'm back and I have a script I created for my colleague, Tom.

Tom called me and wanted to know if there was a way to get time stamps when pinging a server.  To clarify, show a time stamp for each return value from the ping. In addition, the script should run like the Ping -t command and dump the output into a text file.

I researched how to ping within Powershell and found that the Test-Connection cmdlet will do what Tom has requested.  I started by creating a variable that will be used by the While loop

$i = 1

Then, we create the While loop
While ($i = 1){


}
This will run the commands within the loop until $i is something other than 1.

Now, we create the body of the script.  We will run the script against Google (www.google.com)

test-connection www.google.com | select @{N='Time';E={[dateTime}::Now}},@{N='Destination';E={$_.address}},replysize,@{N='Time(ms)';E={$_.Responsetime}} | export-csv -append c:\ping.txt

In the 'select' statement:
@{N='Time';E={[dateTime]::Now}}....This will create a column called 'Time' and this column will hold information from the [dateTime]::Now expression

@{N='Destination';E={$_.address}}...this will create a column called 'Destination' containing the information in the $_.address field

replysize...this is the size of the reply pack in Bytes

@{N='Time(ms)';E={$_.ResponseTime}}...this will create a column called 'Time(ms)' containing the information in the $_.ResponseTime field

The last part of the statement will send the output to a file called Ping.txt in a comma-separated value (CSV) format

In the end, the script will look like this:

$i = 1

While ($i = 1) {

test-connection www.google.com | select @{N='Time';E={[dateTime]::Now}},@{N='Destination';E={$_.address}},replysize,@{N='Time(ms)'; E={$_.ResponseTime}} | export-csv -append c:\ping.txt
 
} 

Some of you may be saying, "There isn't any code that changes $i to something other than 1."  And you would be correct.  This script will run until you manually stop the script, in most cases by using CTRL-C.

The output of the script will look like this:
 


 I hope you find this script helpful.  Be sure to comment if you have any questions.

Mike

No comments:

Post a Comment