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?
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With