Nick Levesque
Nick Levesque

Reputation: 37

Ping Code to reply another color

I am very new to coding so I know very little.

I am writing my first code which is a ping. It can ping any workstation ID that you put in it. I would like that when it pings, the reply would be green and request timed out would be red.

I just want to test it out and learn from it. So far I have this:

$Search = Read-Host "Enter Workstation ID"
$Reply = ping -t $Search

if ($Reply -like "Request Timed Out.") {
    Write-Host $Reply -ForegroundColor Red
}

But that is not working.

Upvotes: 1

Views: 1429

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

If you look at the usage message from ping.exe, you'll see that the -t switch makes ping.exe continue pinging the host until interrupted by Ctrl+C or Ctrl+Break.

That's why it seems like it's "doing nothing".

I would probably go for the Test-Connection cmdlet, rather than ping.exe:

$Hostname = Read-Host "please enter the hostname..."
if(Test-Connection -ComputerName $Hostname -Quiet)
{
    Write-Host "Ping succeeded!" -ForegroundColor Green
}
else
{
    Write-Host "Ping failed!" -ForegroundColor Red
}

It doesn't have a -t parameter, but you can provide a ridiculously high value to the -Count parameter, and make due with that (with a second in between each request, [int]::MaxValue gives you 2^31 seconds, or 68 years worth of pinging):

Test-Connection $Hostname -Count ([int]::MaxValue)

If you sincerely want the -t switch, you can't rely on assignment to a variable, since PowerShell will wait for ping.exe to return (which, intentionally, never happens).

You can however pipe the standard output from ping.exe, and PowerShell's asynchronous runtime will keep them coming for as long as you like:

function Keep-Pinging
{
    param([string]$Hostname)

    ping.exe -t $Hostname |ForEach-Object {
        $Color = if($_ -like "Request timed out*") {
            "Red"
        } elseif($_ -like "Reply from*") {
            "Green"
        } else {
            "Gray"
        }
        Write-Host $_ -ForegroundColor $Color
    }
}

ping away!

Upvotes: 2

Related Questions