Created
May 11, 2021 23:48
-
-
Save Wind010/feb722dd80455551bd75a694bf1b52c8 to your computer and use it in GitHub Desktop.
Powershell script to continuously ping a target host.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .DESCRIPTION | |
| Powershell script to continuously ping a target host. | |
| If logPath is specified, will output rolling logs based off size parameter. | |
| .OUTPUTS | |
| Set-Acl result | |
| .EXAMPLE | |
| PS> .\PingUntil.ps1 'DateTime_to_Stop' 'your_target_host' 'delayInMs' 'logPath' 'maxFileSizeInMB' | |
| or | |
| PS> .\PingUntil.ps1 (Get-Date).AddSeconds(10) 'www.google.com' 100 'C:\somedir\logs\ping.log' 100 | |
| #> | |
| param( | |
| [Parameter(Mandatory=$true)][DateTime] $dtStop, | |
| [Parameter(Mandatory=$true)][string] $targetHost, | |
| [Parameter(Mandatory=$false)][int] $delayInMs = 100, | |
| [Parameter(Mandatory=$false)][string] $logPath = "", | |
| [Parameter(Mandatory=$false)][int] $maxFileSizeInMB = 300 | |
| ) | |
| Function Ping-Until { | |
| param( | |
| [Parameter(Mandatory=$true)][DateTime] $dtStop, | |
| [Parameter(Mandatory=$true)][string] $targetHost, | |
| [Parameter(Mandatory=$false)][int] $delayInMs = 100, | |
| [Parameter(Mandatory=$false)][string] $logPath = "", | |
| [Parameter(Mandatory=$false)][int] $maxFileSizeInMB = 300 | |
| ) | |
| [int] $KB_PER_MB = 1000 | |
| [string] $DateTimeFormat = 'yyyyMMddTHHmm' | |
| [string] $directory = Split-Path $logPath | |
| if ([string]::IsNullOrWhitespace($directory)) | |
| { | |
| $directory = '.' | |
| } | |
| [string] $fileName = [System.IO.Path]::GetFileNameWithoutExtension($logPath) | |
| [string] $ext = [System.IO.Path]::GetExtension($logPath) -Replace '\.', '' | |
| [string] $timestamp = Get-Date -Format $DateTimeFormat | |
| [string] $newFilePath = "$($directory)\$($fileName)_$($timestamp)_$i.$($ext)" | |
| if ((Test-Path -Path $newFilePath) -eq $false) | |
| { | |
| New-Item $newFilePath | Out-Null | |
| } | |
| while((Get-Date) -lt $dtStop) | |
| { | |
| $i = 0 | |
| if ([string]::IsNullOrWhitespace($logPath)) | |
| { | |
| Test-Connection $targetHost | |
| Start-Sleep -m $delayInMs | |
| continue | |
| } | |
| if ((Get-Item $newFilePath).Length -gt ($KB_PER_MB * $maxFileSizeInMB)) | |
| { | |
| $i += 1 | |
| $timestamp = Get-Date -Format $DateTimeFormat | |
| $newFilePath = "$($directory)\$($fileName)_$($timestamp)_$i.$($ext)" | |
| } | |
| $output = Test-Connection $targetHost | |
| Write-Output $output | |
| Out-File -FilePath $newFilePath -InputObject $output -Append | |
| Start-Sleep -m $delayInMs | |
| } | |
| } | |
| Ping-Until $dtStop $targetHost $delayInMs $logPath $maxFileSizeInMB |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment