powershellif-statementinternet-connection

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?


Solution

  • 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:

    if (Test-NetConnection 192.168.1.222 -InformationLevel Quiet) {
        # OK here
    }
    else {
        # Bad here
    }
    
    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