简单的脚本:
"test" | Out-File "C:\existing_file.txt"
$ErrorActionPreference = "Continue"
Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt" -ErrorAction Stop
"hello" | Out-Host
我有这个输出:
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
为什么我在输出中得到“你好”? -ErrorAction停止不起作用??
更新
此代码:
"test" | Out-File "C:\existing_file.txt"
$ErrorActionPreference = "Stop"
Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt"
"hello" | Out-Host
按预期工作。输出中没有“你好”。
Copy-Item ignore -ErrorAction并仅使用$ ErrorActionPreference ??
答案 0 :(得分: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.
来源:Get-Help about_commonparameters
和http://technet.microsoft.com/en-us/library/dd315352.aspx
答案 1 :(得分:0)
奇怪。我在脚本中复制粘贴你的两行,运行它,一切正常:我没有看到“你好”出现。您的“-ErrorAction”应该优先于您在会话级别设置的任何$ ErrorActionPreference。
答案 2 :(得分:0)
你必须要么跑:
Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt" -ErrorAction Continue
"hello" | Out-Host
或设置$ErrorActionPreference="continue"
并运行
Copy-Item "C:\existing_file.txt" "C:\NonExistingDir\file.txt"
"hello" | Out-Host
这是您获得输出的唯一两种方式。因此,请确保您正在做您声称要做的事情。