I'm writing a script to test our internet connection periodically and can't figure out how to write an if statement that doesn't cause powershell to fail on error, or return a true/false from Test-Connection or Test-NetConnection to a specific ip address.
I've tried
if(Test-NetConnection 192.168.1.222) { echo "OK"} else {echo "Not OK"}
That always returns OK.
Can a text be done that returns a true/false result that can be used in a conditional expression?
Test-NetConnectionwithout specifying a-Portis essentially an icmp echo request, if you're just testing this then probably would be better to use justTest-Connection. Solution is to use:-InformationLevel QuietforTest-NetConnection:-QuietforTest-Connection:Reason why your condition always evaluates to
$trueis becauseTest-NetConnectionoutputs an object no matter if failed or not:And objects when coerced to a
boolalways evaluate totrue: