Convert Test-Connection into Boolean

Glowie picture Glowie · Jul 30, 2013 · Viewed 19.7k times · Source

I am using Powershell version 2, so I am unable to use Ping-Host as explained here Is there a way to treat Ping-Host as a boolean in PowerShell?

I can use test connection, i.e.

Test-Connection *ip_address* -count 1

I am trying to make this into a boolean, but it is not working

if ($(test-connection server -count 1).received -eq 1) { write-host "blah" } else {write-host "blah blah"}

The server I am able to ping outputs "blah blah", as if I am not able to ping it.

On the other hand, if I ping an unreachable server, I get error message

Test-Connection : Testing connection to computer server failed: Error due to lack of resources At line:1 char:22 + if ($(test-connection <<<< server -count 1).received -eq 1) { write-host "blah" } else {write-host "blah blah"} + CategoryInfo : ResourceUnavailable: (server:String) [Test-Connection], PingException + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

And at the end it still outputs "blah blah".

How to fix?

Answer

Shay Levy picture Shay Levy · Jul 30, 2013

Try the -Quiet switch:

Test-Connection server -Count 1 -Quiet    

-Quiet [<SwitchParameter>]
    Suppresses all errors and returns $True if any pings succeeded and $False if all failed.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Accept wildcard characters?  false