Convert Test-Connection into Boolean Convert Test-Connection into Boolean powershell powershell

Convert Test-Connection into Boolean


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


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"}


a better one liner which we use at production

function test_connection_ipv4($ipv4) { if (test-connection $ipv4 -Count 1 -ErrorAction SilentlyContinue ) {$true} else {$false} }

usage example 1:

test_connection_ipv4 10.xx.xxx.50True

usage example 2:

test_connection_ipv4 10.xx.xxx.51False