Powershell - 捕获 [System.???] - 我如何找到 ???要使用吗?

问题描述 投票:0回答:1

在特别深的目录下,代码:

$files = Get-ChildItem -Path $d.FullName -File -Recurse -ErrorAction SilentlyContinue
导致

Get-Childitem : The script failed due to call depth overflow.
At K:\proj000\QC\sully\FindLatestTryCatch_format.ps1:8 char:10
+ $files = Get-Childitem -Path $d.Fullname -File -Recurse -ErrorAction  ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (0:Int32) [Get-ChildItem], ScriptCallDepthException
    + FullyQualifiedErrorId : CallDepthOverflow,Microsoft.PowerShell.Commands.GetChildItemCommand

我想将 GCI 调用包装在 try-catch 块中,但我不知道在方括号内的

catch [???] {}
中指定什么。我可以从显示的错误消息中提取文本吗? $Error 的某些属性?

powershell try-catch
1个回答
0
投票

如果您查看错误,在

CategoryInfo
中您可以看到它抛出的异常类型:

InvalidOperation: (0:Int32) [Get-ChildItem], ScriptCallDepthException

所以基本上:

[System.Management.Automation.ScriptCallDepthException]::new()

如果你想捕获特定的异常类型,那么你可以这样做:

try {
    $files = Get-ChildItem -Path $d.FullName -File -Recurse -ErrorAction SilentlyContinue
}
catch [System.Management.Automation.ScriptCallDepthException] {
    # handle call depth exception
}
© www.soinside.com 2019 - 2024. All rights reserved.