Reputation: 43077
I need to ping things in Windows and know what time pings were received or missed; the timestamps should reflect 24-hour time (instead of an AM/PM suffix).
How can I do this in Powershell?
Upvotes: 4
Views: 11165
Reputation: 7479
it seems that you want the display of both successful and failed pings AND that you want to handle multiple addresses. this should do the job ...[grin]
what it does ...
HH
is for 24 hour, hh
is for 12 hour, tt
would be the AM
or PM
stuff. while
to while ($True)
instead of using a counter. i would just set the $RepeatCount
to something like 666
. while
trigger foreach
loop -f
string format operator -f
string format operator and pattern string to show the info here's the code ...
$IP_List = @(
'127.0.0.1'
'10.0.0.1'
'1.1.1.1'
)
$TimeStampFormat = 'yyyy-MM-dd HH:mm:ss'
$NoResponse = '__No Response__'
$RepeatCount = 3
$Counter = 1
while ($Counter -le $RepeatCount)
{
'______ Repeat Count = {0, 3}' -f $Counter
foreach ($IPL_Item in $IP_List)
{
$Result = Test-Connection -ComputerName $IPL_Item -Count 1 -ErrorAction SilentlyContinue |
Select-Object -Property Address, ResponseTime
$TimeStamp = [datetime]::Now.ToString($TimeStampFormat)
if (-not $Result)
{
$PingData = @($TimeStamp, $env:COMPUTERNAME, $IPL_Item, $NoResponse)
}
else
{
$PingData = $($TimeStamp, $env:COMPUTERNAME, $Result.Address, $Result.ResponseTime)
}
'{0} - From = {1, -10} - To = {2, -16} - ResponseTime = {3, 4}' -f $PingData
}
$Counter++
}
output ...
______ Repeat Count = 1
2019-06-01 21:24:50 - From = [MySysName] - To = 127.0.0.1 - ResponseTime = 0
2019-06-01 21:24:54 - From = [MySysName] - To = 10.0.0.1 - ResponseTime = __No Response__
2019-06-01 21:24:54 - From = [MySysName] - To = 1.1.1.1 - ResponseTime = 20
______ Repeat Count = 2
2019-06-01 21:24:54 - From = [MySysName] - To = 127.0.0.1 - ResponseTime = 0
2019-06-01 21:24:58 - From = [MySysName] - To = 10.0.0.1 - ResponseTime = __No Response__
2019-06-01 21:24:58 - From = [MySysName] - To = 1.1.1.1 - ResponseTime = 19
______ Repeat Count = 3
2019-06-01 21:24:58 - From = [MySysName] - To = 127.0.0.1 - ResponseTime = 0
2019-06-01 21:25:02 - From = [MySysName] - To = 10.0.0.1 - ResponseTime = __No Response__
2019-06-01 21:25:02 - From = [MySysName] - To = 1.1.1.1 - ResponseTime = 20
Upvotes: 0
Reputation: 43077
You can timestamp pings wth a foreach()
loop; Get-Date
can take a format string:
C:\> powershell
PS C:\> ping.exe -t 4.2.2.2 | Foreach{"{0} - {1}" -f (Get-Date -f "yyyyMMdd HH:mm:ss"),$_}
20190601 14:33:03 -
20190601 14:33:03 - Pinging 4.2.2.2 with 32 bytes of data:
20190601 14:33:03 - Reply from 4.2.2.2: bytes=32 time=70ms TTL=123
20190601 14:33:04 - Reply from 4.2.2.2: bytes=32 time=71ms TTL=123
20190601 14:33:05 - Reply from 4.2.2.2: bytes=32 time=70ms TTL=123
Upvotes: 7