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"}
}
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"}
}
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 {
"$_"
}
}
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"
}
}