Sloan Thrasher
Sloan Thrasher

Reputation: 5040

Test for connection to the internet in a powershell script?

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?

Upvotes: 3

Views: 4177

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60693

Test-NetConnection without specifying a -Port is essentially an icmp echo request, if you're just testing this then probably would be better to use just Test-Connection. Solution is to use:

  • -InformationLevel Quiet for Test-NetConnection:
if (Test-NetConnection 192.168.1.222 -InformationLevel Quiet) {
    # OK here
}
else {
    # Bad here
}
  • -Quiet for Test-Connection:
if (Test-Connection 192.168.1.222 -Quiet) {
    # OK here
}
else {
    # Bad here
}

Reason why your condition always evaluates to $true is because Test-NetConnection outputs an object no matter if failed or not:

PS ..pwsh\> Test-NetConnection doesnotexist.xyz

WARNING: Name resolution of doesnotexist.xyz failed

ComputerName   : doesnotexist.xyz
RemoteAddress  : 
InterfaceAlias : 
SourceAddress  : 
PingSucceeded  : False

And objects when coerced to a bool always evaluate to true:

PS ..pwsh\> [bool] (Test-NetConnection doesnotexist.xyz)

WARNING: Name resolution of doesnotexist.xyz failed
True

Upvotes: 3

Related Questions