问题描述
我的情况:
$ErrorActionPreference = "Stop";
"1 - $ErrorActionPreference;"
Get-ChildItem NoSuchFile.txt -ErrorAction SilentlyContinue;
"2 - $ErrorActionPreference;"
Get-ChildItem NoSuchFile.txt -ErrorAction Stop;
"3 - $ErrorActionPreference;"
输出:
1 - 停止;
2 - 停止;
并显示错误...
现在,
$ErrorActionPreference = "Stop";
"1 - $ErrorActionPreference;"
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
"2 - $ErrorActionPreference;"
输出:
1 - 停止;
并显示错误...
为什么 -ErrorAction SilentlyContinue) 对于 Get-PSSessionConfiguration 不起作用?
Why doesn't work -ErrorAction SilentlyContinue) for Get-PSSessionConfiguration ?
更新:
现在,
$ErrorActionPreference = "Continue"
"1 - $ErrorActionPreference;"
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
"2 - $ErrorActionPreference;"
输出:
1 - 继续;
2 - 继续;
现在,
$ErrorActionPreference = "SilentlyContinue"
"1 - $ErrorActionPreference;"
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
"2 - $ErrorActionPreference;"
输出:
1 - SilentlyContinue;
2 - 静默继续;
这个参考:
ErrorAction
无处不在的参数可用于使用参数值 SilentlyContinue
来消除非终止错误,并且可用于将非终止错误转换为使用以下方法的终止错误参数值Stop
.但是,它无法帮助您忽略终止错误,在这种情况下,Stop-Transcript 会引发终止错误.如果您想忽略,请使用 try/catch 例如:
The ErrorAction
ubiquitous parameter can be used to silence non-terminating errors using the parameter value SilentlyContinue
and it can be used to convert non-terminating errors to terminating errors using the parameter value Stop
. However it can't help you ignore terminating errors and in this case Stop-Transcript is throwing a terminating error. If you want to ignore, use a try/catch e.g.:
try { Stop-Transcript } catch {}
推荐答案
适合我的解决方案:
$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {
#Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference
或者使用 try-catch
Or use try-catch
try {
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
}
catch {
}
这篇关于Get-PSSessionConfiguration 的 ErrorActionPreference 和 ErrorAction SilentlyContinue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!