PowerShell递归深层目录触发调用深度溢出,如何确定catch的异常类型?
解决Get-ChildItem递归调用的异常捕获问题
问题场景
在层级极深的目录下执行以下PowerShell代码时:
$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
需要将该调用包裹在try-catch代码块中,但不清楚catch [???] {}内应指定的异常类型,希望从错误信息或$Error变量中获取该类型。
获取异常类型的方法
1. 直接从错误信息提取
报错信息的CategoryInfo字段已经明确给出了异常类型:ScriptCallDepthException,其完整命名空间为Microsoft.PowerShell.Commands.ScriptCallDepthException。
对应的try-catch代码示例:
try { # 必须将ErrorAction设为Stop,否则错误不会被转为可捕获的终止错误 $files = Get-ChildItem -Path $d.FullName -File -Recurse -ErrorAction Stop } catch [Microsoft.PowerShell.Commands.ScriptCallDepthException] { # 自定义异常处理逻辑 Write-Warning "目录层级过深导致调用溢出:$($_.Exception.Message)" }
2. 通过$Error变量查询
如果错误已经发生,可通过$Error变量查看完整的异常类型信息:
- 执行以下命令获取异常的完整类型名:
返回结果即为$Error[0].Exception.GetType().FullNameMicrosoft.PowerShell.Commands.ScriptCallDepthException - 也可以直接查看异常对象的类型细节:
$Error[0].Exception.GetType()
内容的提问来源于stack exchange,提问作者pteranodon
相关产品推荐
相关产品推荐

