让我们以这个脚本为例:
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
try
{
echo "ErrorActionPreference = $ErrorActionPreference"
Copy-Item "this_is_a_bad_path"
Write-Host "Did not catch error"
}
catch
{
Write-Host "Caught Error"
}这与以下输出的预期效果相同:
ErrorActionPreference = Stop
Caught Error但是,如果我将-verbose添加到行中,并给出Copy-Item -verbose "this_is_a_bad_path",则不再使用$ErrorActionPrefrence,并得到以下输出:
ErrorActionPreference = Stop
Copy-Item : Cannot find path 'C:\Users\porter.bassett\this_is_a_bad_path' because it does not exist.
At C:\Users\porter.bassett\dot.ps1:7 char:3
+ Copy-Item -verbose "this_is_a_bad_path"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\porter...s_is_a_bad_path:String) [Copy-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
Did not catch error 为了让它在-verbose打开、打开的情况下正常工作,我必须将-ErrorAction Stop添加到给出Copy-Item -verbose "this_is_a_bad_path" -ErrorAction Stop的代码行中
为什么在使用-Verbose时不能依赖$ErrorActionPreference
发布于 2016-05-04 01:28:30
这也是Technet上讨论的PowerShell中的一个特性/错误:Verbose common parameter disables ErrorActionPreference。
这个特性/错误在PowerShell 4和最新版本5中也存在。
发布于 2017-04-13 19:24:56
好吧,我不知道为什么,但是这个triple face palm问题(好吧,至少是IMHO),在开放源码的PS代码中仍然有效:
/// <summary>
/// ErrorAction tells the command what to do when an error occurs
/// </summary>
/// <exception cref="System.Management.Automation.ExtendedTypeSystemException">
/// (get-only) An error occurred accessing $ErrorAction.
/// </exception>
/// <remarks>
/// This is a common parameter via class CommonParameters.
/// </remarks>
internal ActionPreference ErrorAction
{
get
{
// Setting CommonParameters.ErrorAction has highest priority
if (IsErrorActionSet)
return _errorAction;
// Debug takes preference over Verbose
if (Debug)
return ActionPreference.Inquire;
if (Verbose)
return ActionPreference.Continue; *** WTF!?! ***
// fall back to $ErrorAction
if (!_isErrorActionPreferenceCached)
{
bool defaultUsed = false;
_errorAction = Context.GetEnumPreference<ActionPreference>(SpecialVariables.ErrorActionPreferenceVarPath, _errorAction, out defaultUsed);
_isErrorActionPreferenceCached = true;
}
return _errorAction;
}发布于 2017-01-01 20:45:52
最好的办法是为模块中的每个命令指定erroraction。
write-host foo -ErrorAction Stop
更新:这篇博文很有帮助。它解释了全局var继承如何导致观察到的行为。
https://stackoverflow.com/questions/37006493
复制相似问题