为什么-Verbose禁用$ ErrorActionPreference的使用?

Por*_*Man 7 powershell

我们来看看这个剧本:

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"
}
Run Code Online (Sandbox Code Playgroud)

这与以下输出一样正常工作:

ErrorActionPreference = Stop
Caught Error
Run Code Online (Sandbox Code Playgroud)

但是,如果我添加-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 
Run Code Online (Sandbox Code Playgroud)

为了让它在-verbose转动时正常工作,我必须添加-ErrorAction Stop到给我的线上Copy-Item -verbose "this_is_a_bad_path" -ErrorAction Stop

为什么我不能$ErrorActionPreference在使用时依赖-Verbose

Ama*_*rma 2

这是 PowerShell 中的一个功能/错误,Technet 上也对此进行了讨论:详细通用参数禁用 ErrorActionPreference

PowerShell 4 和最新版本 5 中也存在此功能/错误。

  • “更好”的讨论链接:[向 Cmdlet 添加 -Verbose 可防止脚本因错误而终止](https://social.technet.microsoft.com/Forums/systemcenter/en-US/b76eccae-4484-43ec-a3dc- d4bc581124c2/向 cmdlet 添加详细信息以防止错误终止脚本?forum=winserverpowershell) (2认同)