CTF: Ping Script

I just took a straight forward approach to this script with a little bit of humour for Gav and Kelvin (The judges) added in. I think the main challenge was to use PowerShell 7 and -parallel so I just made a reasonably nice script around that:

$DevicesToPing = @("192.168.26.90", "192.168.26.1", "192.168.26.50")
$NumberOfPings = 2
$NumberToRunInParallel = 10

# Version Check
if ((get-host).version.major -ne 7) {
    Write-Error "I am terribly sorry but could you please install Powershell 7 so we can use -parallel" -foregroundcolor Red
    exit 1
}

# Declare function
function Get-PingResults {
    param(
        [string[]]$DevicesToPing,
        [int]$NumberOfPings = 4,
        [int]$NumberToRunInParallel = 10
    )

    # Build our results
    $Results = $DevicesToPing | ForEach-Object -ThrottleLimit $NumberToRunInParallel -Parallel {
        $HostResult = Test-Connection $_ -count $using:NumberOfPings
        $SuccessfulPings = (($HostResult | Where-Object { $_.Status -eq "Success" } | measure-object).count)
        if ($using:NumberOfPings -eq $SuccessfulPings) {
            $Status = "Host Alive"
        }
        elseif ($SuccessfulPings -ne 0) {
            $Status = "Host Experiancing Packet Loss"
        }
        else {
            $Status = "Host Down"
        }

        # Make a nice object to return the results
        [PSCustomObject]@{
            Host              = $_
            Status            = $Status
            SuccessfulPings   = $SuccessfulPings
            PacketLossPercent = (($using:NumberOfPings - $SuccessfulPings) / $using:NumberOfPings) * 100
            AverageLatency    = ($HostResult | Measure-Object Latency -sum).sum / $using:NumberOfPings
            RawResults        = $HostResult
        }
    }

    Return $Results
}

# Run the function
$Settings = @{
    DevicesToPing = $DevicesToPing
    NumberOfPings = $NumberOfPings
    NumberToRunInParallel = $NumberToRunInParallel
}
$PingResults = Get-PingResults @Settings

# Brown Nose
if ($env:UserName -match "Kelvin" -or $env:UserName -match "Tegelaar" -or $env:UserName -match "Gavin" -or $env:UserName -match "Stone") {
    Write-Host "You are an amazing person, have a lovely day!" -ForegroundColor Green
}

# Return our result object
$PingResults

You may also like...