问题出在哪里
我尝试运行以下内容:
try {
$Content | Out-File "SomePath.txt" -ErrorAction Stop
}
catch {
echo "Error!!!"
}
echo "Still here!"
我抓到了什么(精神上抓到的是…(
根据我所了解到的,Powershell中有两种类型的异常——终止和非终止
从这里:
有两种类型的异常:终止和非终止。终止异常将停止运行脚本。非终止异常只写入错误管道
为了捕获try-catch
块中的异常,该异常必须终止
因此,您需要将$ErrorActionPreference
设置为Stop
,或者运行cmdlet具有CCD_ 4标志
因此,以下代码将终止脚本:
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
(时,我注意到执行CCD_ 8块。输出:
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
块中时,为什么不终止脚本???
如果我正确地回答了您的问题,这将导致命令终止异常,但不会导致脚本终止异常。命令终止可以通过try捕获,但如果没有捕获到,脚本仍然会继续。命令可能无法完成自己的操作。尽管很难想出一个这样的例子。
try {get-content text | out-file FolderNotExistout } 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 FolderNotExistout
echo "Still here!"
out-file : Could not find a part of the path 'C:UsersjsfooFolderNotExistout'.
At C:Usersjsfootry.ps1:1 char:20
+ get-content text | out-file FolderNotExistout
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
Still here!
# out2 still gets created
get-content text | set-content FolderNotExistout,out2