为什么我的 powershell try catch 代码只打印错误?
why my powershell try catch codes are printing only error?
$MDservices = ""
$tempservices = ""
尝试{
$alerter = Get-Service Alerter
if($alerter.Status -eq 'Running'){
$alerter = Out-String -InputObject $alerter.DisplayName
$MDservices = $tempservices + $alerter
} else {
continue
}
}
抓住
{
write "somethings wrong"
}
这是我的 powershell try catch 代码。
我希望这个输出是写“somethings wrong”因为我的电脑没有 'Alerter' 服务
但它的输出是打印错误
伙计们,我在做什么?帮助我:(
如果try
块没有产生终止错误,它不会进入Catch
块。这是由 -ErrorAction
参数控制的。默认情况下它使用 Continue
。所以只需更改
# This will generate terminating error and move to Catch Block.
$alerter = Get-Service Alerter -ErrorAction Stop
很可能是因为您的默认 $ErrorActionPreference 值。
尝试以下操作:
try
{ $alerter = Get-Service Alerter -ErrorAction Stop
if($alerter.Status -eq 'Running') {
$alerter = Out-String -InputObject $alerter.DisplayName
$MDservices = $tempservices + $alerter
}
else {
continue
}
}
catch
{ Write-Host "somethings wrong"
}
finally
{
Write-Host "cleaning up ..."
}
$MDservices = ""
$tempservices = ""
尝试{
$alerter = Get-Service Alerter
if($alerter.Status -eq 'Running'){
$alerter = Out-String -InputObject $alerter.DisplayName
$MDservices = $tempservices + $alerter
} else {
continue
}
}
抓住 {
write "somethings wrong"
}
这是我的 powershell try catch 代码。 我希望这个输出是写“somethings wrong”因为我的电脑没有 'Alerter' 服务 但它的输出是打印错误
伙计们,我在做什么?帮助我:(
如果try
块没有产生终止错误,它不会进入Catch
块。这是由 -ErrorAction
参数控制的。默认情况下它使用 Continue
。所以只需更改
# This will generate terminating error and move to Catch Block.
$alerter = Get-Service Alerter -ErrorAction Stop
很可能是因为您的默认 $ErrorActionPreference 值。
尝试以下操作:
try
{ $alerter = Get-Service Alerter -ErrorAction Stop
if($alerter.Status -eq 'Running') {
$alerter = Out-String -InputObject $alerter.DisplayName
$MDservices = $tempservices + $alerter
}
else {
continue
}
}
catch
{ Write-Host "somethings wrong"
}
finally
{
Write-Host "cleaning up ..."
}