You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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().FullName
    
    返回结果即为Microsoft.PowerShell.Commands.ScriptCallDepthException
  • 也可以直接查看异常对象的类型细节:
    $Error[0].Exception.GetType()
    

内容的提问来源于stack exchange,提问作者pteranodon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:27:03