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

如何捕获Get-Childitem访问目录被拒绝时的错误?

问题:无法用try/catch捕获Get-ChildItem的权限错误

尝试用try/catch块捕获Get-ChildItem的UnauthorizedAccessException错误,但始终失败,代码片段如下:

if((Test-Path .\test.txt)){
    $key = Get-Content -Path .\test.txt
} else {
  write-host "test.txt file not found in current folder. Searching for it in other folders." -ForegroundColor DarkCyan
  try {
        $key = @(gci -path $env:USERPROFILE -file test.txt -Recurse -ErrorVariable ers )[0]  
      } catch [System.UnauthorizedAccessException]{ 
        write-warning -Message "Folder offlimits" 
      } catch [RuntimeException]{
        write-warning -Message "Some other error occured"  
      } finally {
        write-host $key.FullName
      }
            
}

执行后,$ers中出现的错误内容:

gci : Access to the path 'C:\User\Search\Data' is denied.
At line:6 char:26
+ ...    $key = @(gci -path $env:USERPROFILE -file test.txt -Recurse  -Error ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\User\Search\Data:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

解决思路

  • 核心原因:PowerShell的try/catch仅捕获终止性错误,而Get-ChildItem遇到权限拒绝时抛出的是非终止性错误,这类错误默认不会中断执行,也不会触发catch块。

  • 修正方法:在gci命令中添加-ErrorAction Stop参数,强制将非终止性错误转为终止性错误,这样就能被try/catch捕获:

if((Test-Path .\test.txt)){
    $key = Get-Content -Path .\test.txt
} else {
  write-host "test.txt file not found in current folder. Searching for it in other folders." -ForegroundColor DarkCyan
  try {
        # 添加-ErrorAction Stop参数,将非终止错误转为终止错误
        $key = @(gci -path $env:USERPROFILE -file test.txt -Recurse -ErrorVariable ers -ErrorAction Stop )[0]  
      } catch [System.UnauthorizedAccessException]{ 
        write-warning -Message "Folder offlimits" 
      } catch [System.Exception]{
        # 兜底捕获其他终止性错误,$_可查看错误详情
        write-warning -Message "Some other error occurred: $_"  
      } finally {
        # 增加空值判断,避免$key为空时报错
        if ($key) { write-host $key.FullName }
      }
            
}
  • 额外说明:
    • 若不想针对单个命令设置,也可以在try块前临时修改全局错误偏好:$originalErrorAction = $ErrorActionPreference; $ErrorActionPreference = 'Stop',执行完成后再恢复原设置。
    • 捕获System.Exception可以兜底处理所有未明确指定的终止性错误,方便排查其他未知问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:27:25