首页 > 解决方案 > 逐个文件捕获“Get-ChildItem”错误

问题描述

我正在使用Get-ChildItem -Recurse搜索目录。我不能保证所有Get-ChildItem将被击中的东西都可以访问。我想记录这些失败,但不让整个Get-ChildItem -Recurse命令失败。现在我有

Get-ChildItem -Recurse $targetdir -ErrorAction Inquire `
        | where { $_.Name -eq $name } `
        | foreach {
            echo-indented "Found $(hash $_) at $($_.FullName)"
            $_
        }

有问题的代码是-ErrorAction Inquire. 如果我这样做了-ErrorAction Stop,我将不得不在某个地方放置一个try-catch。它必须围绕整个管道,对吗?在这种情况下,将不会找到并写出在不可访问项之后找到的子项。那我还能做什么?

标签: powershell

解决方案


您可以使用-ErrorVariablecommon 参数将错误保存到变量中。

Get-ChildItem -recurse foo -ErrorVariable err
$err

推荐阅读