Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Test-Connection into Boolean

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?

like image 294
Glowie Avatar asked Jul 30 '13 17:07

Glowie


2 Answers

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
like image 184
Shay Levy Avatar answered Nov 16 '22 15:11

Shay Levy


Received isn't a property of the object that Test-Connection returns, so $(test-connection server -count 1).received evaluates to null. You're overthinking it; just use if (Test-Connection -Count 1). To suppress the error message, use -ErrorAction SilentlyContinue, or pipe the command to Out-Null. Either of the following will work:

if (Test-Connection server -Count 1 -ErrorAction SilentlyContinue) { write-host "blah" } else {write-host "blah blah"}

or

if (Test-Connection server -Count 1 | Out-Null) { write-host "blah" } else {write-host "blah blah"}
like image 38
Adi Inbar Avatar answered Nov 16 '22 13:11

Adi Inbar