Modro
Modro

Reputation: 436

Try Catch wont Catch

When I'm using try{} catch{} pinging these servers I only get a cmdlet error instead of the catch in try-catch... What is the problem here?

foreach($s in $servers)
{
    try{Test-Connection $s.server -Count 1}
    catch{ Write-Host "error"}
}

Upvotes: 3

Views: 298

Answers (3)

Maximilian Burszley
Maximilian Burszley

Reputation: 19644

By default, cmdlets throw non-script-terminating errors which a try/catch does not handle. You can change this behavior by using the $ErrorActionPreference automatic variable, or the -ErrorAction common parameter:

# or `$ErrorActionPreference = 'Stop'`
foreach ($s in $servers) {
    try {
        Test-Connection -TargetName $s.server -Count 1 -ErrorAction Stop
    }
    catch {
        "$_"
    }
}

Upvotes: 9

Srinwantu Ghosh
Srinwantu Ghosh

Reputation: 1

Please check the header name in input file. try{Test-Connection $s.server -Count 1}

Upvotes: -2

Mark Harwood
Mark Harwood

Reputation: 2415

Test-Connection doesn't provide a "Terminating Error" when something goes wrong. This means that the try/catch isn't triggered. You can solve this by adding -ErrorAction Stop to the Test-Connection command.

foreach($s in $servers)
{
    try{
        Test-Connection $s.server -Count 1 -ErrorAction Stop
    }catch{
        "error"
    }
}

Upvotes: 4

Related Questions