Reputation: 18123
I have a PowerShell script that need to check if there is internet connectivity before running the rest of the script. For the example using Test-Connection
if (Test-Connection example.com) {
Write-Host "Connection available"
# do-other things
} else {
Write-Host "No internet connection"
Exit
}
The problem with this approach is if there is no connection it gives this error message:
Testing connection to computer 'example.com' failed: Cannot resolve the | target name.
and then the actual message follows No internet connection
but the idea was to have it move to the else clause not giving that error message when there no connection.
For example when there is no internet connection the error message No internet connection
is printed, that's it, nothing else. How can I achieve this.
Upvotes: 1
Views: 3922
Reputation: 9975
Per @mukunda's answer, Test-Connection
has a -Quiet
switch that ignores errors and returns a boolean result - see the documentation for Test-Connection for the details.
Note there's some perhaps unexpected behaviour if you're testing multiple sites in a single call:
If any ping to a given target succeeds, $True is returned
In other words, even if some sites fail you'd still get $true
returned.
Note that in general you can also suppress errors in cmdlets with -ErrorAction "SilentlyContinue"
, and check the return value after:
$result = Test-Connection -Ping "www.example.org" -ErrorAction "SilentlyContinue";
if ($null -eq $result)
{
Write-Host "No internet connection"
Exit
}
else
{
Write-Host "Connection available"
# do-other things
}
Upvotes: 0
Reputation: 2995
Test-Connection
doesn't seem to have something that we can catch with try-catch, but there is a -Quiet
parameter that may do what you want. It translates the output to a simple boolean.
Testing without and with an internet connection:
Upvotes: 2