Reputation: 436
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
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
Reputation: 1
Please check the header name in input file. try{Test-Connection $s.server -Count 1}
Upvotes: -2
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