抛出异常时,出文件行为异常

时间:2020-07-16 12:01:58

标签: powershell exception try-catch

出现了什么问题

我尝试运行以下命令:

try {
 $Content | Out-File "SomePath.txt" -ErrorAction Stop
}
catch {
  echo "Error!!!"
}

echo "Still here!"

我抓到的(精神上抓到的是...)

从我发现的情况来看,Powershell中有两种异常类型-终止和非终止。
From here

有两种例外:终止和非终止。终止异常会停止 运行脚本。非终止异常仅写入错误管道。

并且为了在try-catch块中捕获异常,该异常必须终止。
因此,您需要将$ErrorActionPreference设置为Stop,或运行cmdlet 带有-ErrorAction Stop标志。
因此,以下代码将终止脚本:

try {
 Get-Content "Path-Doesnt-Exist" -ErrorAction Stop
}
catch {
 echo "Dang!"
}
echo "Still here!"

将输出Dang!

以下代码:

 Get-Content "Path-Doesnt-Exist"
 echo "Still here!"

将输出红色错误,然后输出Still here!

到目前为止一切顺利!

问题

运行第一个代码段(使用Out-File)时,我注意到 catch块已执行。输出:

Error!!!
Still here!

哪个好。
但是后来我注意到,如果我在没有-ErrorAction Stop的情况下运行它,我会得到相同的结果,
这令人惊讶。但是后来我发现这是一个终止的例外,因此您不需要
ErrorAction设置为Stop,不仅不需要,而且也不起作用。

然后我发现如果我跑步

$Content | Out-File "Path-Doesnt-Exist" -ErrorAction Stop
echo "Still here!"

(我希望脚本停止执行) 打印:

<some red error>
Still here!

最后

这是怎么回事?如果从Out-File cmdlet抛出异常,则
正在终止,那么为什么脚本在未终止时没有终止
try-catch块中?

1 个答案:

答案 0 :(得分:0)

如果我正确地遵循了您的问题,这将导致命令终止异常,但不会导致脚本终止异常。可以通过尝试捕获命令终止,但是如果未捕获,脚本仍会继续。该命令可能无法完成其自身的动作。尽管很难举出一个例子。

try {get-content text | out-file FolderNotExist\out } catch {'no' }

no
# out-file can't output to an array of paths
# set-content would not have a terminating exception
get-content text | out-file FolderNotExist\out
echo "Still here!"

out-file : Could not find a part of the path 'C:\Users\js\foo\FolderNotExist\out'.
At C:\Users\js\foo\try.ps1:1 char:20
+ get-content text | out-file FolderNotExist\out
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Out-File], DirectoryNotFoundException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

Still here!
# out2 still gets created
get-content text | set-content FolderNotExist\out,out2