Wednesday 22 February 2023

PowerShell Script to ping an host IP address for a set amount of hours

This script will ping a host for the amount of hours you set when you run it,  it will then display any failures and the times it failed, while also output the results at the end of the time or when the user interrupts the script.

$ipAddress = Read-Host "Enter IP address to ping"
$duration = Read-Host "Enter duration of ping test in hours"
$successCount = 0
$failureCount = 0
$startTime = Get-Date
try {
    while ((Get-Date) -lt ($startTime.Addhours($duration))) {
        $pingResult = Test-Connection $ipAddress -Count 1 -ErrorAction SilentlyContinue
        if ($pingResult.StatusCode -eq 0) {
        } else {
            Write-Host "Ping failed at $(Get-Date)" -ForegroundColor Red
Finally {
    Write-Host "Ping test complete. Results:" -ForegroundColor Yellow
    Write-Host "  Successful pings: $successCount" -ForegroundColor Green
    Write-Host "  Failed pings: $failureCount" -ForegroundColor Red

No comments:

Post a Comment