-ErrorAction停止在Copy-Item中工作

Jac*_*128 6 powershell

简单的脚本:

"test" | Out-File "C:\existing_file.txt"
$ErrorActionPreference = "Continue"
Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt" -ErrorAction Stop
"hello" | Out-Host
Run Code Online (Sandbox Code Playgroud)

我有这个输出:

Copy-Item : Could not find a part of the path "C:\NonExistingDir\file.txt".
C:\Users\ESavin\AppData\Local\Temp\d3d410e0-79b3-4736-b7e7-5aba1ab11a12.ps1:1 ????:10
+ Copy-Item <<<<  "C:\existing_file.txt" "C:\NonExistingDir\file.txt" -ErrorAction Stop
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand

hello
Run Code Online (Sandbox Code Playgroud)

为什么我在输出中得到"你好"?-ErrorAction停止不工作?

更新:

这段代码:

"test" | Out-File "C:\existing_file.txt"
$ErrorActionPreference = "Stop"
Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt"
"hello" | Out-Host
Run Code Online (Sandbox Code Playgroud)

按预期工作.输出中没有"你好".

Copy-Item ignore -ErrorAction并仅使用$ ErrorActionPreference ??

Tom*_*Tom 5

如帮助所示,ErrorAction参数对终止错误没有影响.

    The ErrorAction parameter has no effect on terminating errors (such as
    missing data, parameters that are not valid, or insufficient 
    permissions) that prevent a command from completing successfully.
Run Code Online (Sandbox Code Playgroud)

来源:Get-Help about_commonparametershttp://technet.microsoft.com/en-us/library/dd315352.aspx


Dav*_*ant 0

奇怪的。我将你的两行复制粘贴到脚本中,运行它,一切正常:我没有看到“你好”出现。您的“-ErrorAction”应优先于您在会话级别设置的任何 $ErrorActionPreference。