Powershell try/catch with test-connection Powershell try/catch with test-connection powershell powershell

Powershell try/catch with test-connection


try is for catching exceptions. You're using the -Quiet switch so Test-Connection returns $true or $false, and doesn't throw an exception when the connection fails.

As an alternative you can do:

if (Test-Connection -computername $computer -Quiet -Count 1) {    # succeeded do stuff} else {    # failed, log or whatever}


The Try/Catch block is the better way to go, especially if you plan to use a script in production. The OP's code works, we just need to remove the -Quiet parameter from Test-Connection and trap the error specified. I tested on Win10 in PowerShell 5.1 and it works well.

    try {        Write-Verbose "Testing that $computer is online"        Test-Connection -ComputerName $computer -Count 1 -ErrorAction Stop | Out-Null        # any other code steps follow    catch [System.Net.NetworkInformation.PingException] {        Write-Warning "The computer $(($computer).ToUpper()) could not be contacted"    } # try/catch computer online?

I've struggled through these situations in the past. If you want to be sure you catch the right error when you need to process for it, inspect the error information that will be held in the $error variable. The last error is $error[0], start by piping it to Get-Member and drill in with dot notation from there.

Don Jones and Jeffery Hicks have a great set of books available that cover everything from the basics to advanced topics like DSC. Reading through these books has given me new direction in my function development efforts.