Convert test connection to logical

I am using Powershell version 2, so I cannot use Ping-Host as described here Is there a way to treat Ping-Host as logical in PowerShell?

I can use a test connection, i.e.

Test-Connection *ip_address* -count 1 

I try to make it logical, but it does not work

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

The server on which I can ping displays "blah blah" as if I could not carry it.

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

Testing: failed to test connection to the computer server: Error due to lack of resources. In 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 in the end, he still displays blah blah.

How to fix?

+8
powershell ping
source share
3 answers

Received is not a property of the object that Test-Connection returns, so $(test-connection server -count 1).received is null. You overfulfill it; just use if (Test-Connection -Count 1) . To suppress the error message, use -ErrorAction SilentlyContinue or issue a command to Out-Null . One of the following actions will be performed:

 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"} 
+10
source share

Try using 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 
+18
source share

the best one liner we use in manufacturing

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

Use case 1:

 test_connection_ipv4 10.xx.xxx.50 True 

Use case 2:

 test_connection_ipv4 10.xx.xxx.51 False 
0
source share

All Articles