【问题标题】:Catching paths of inaccessible folders from Get-Childitem从 Get-Childitem 捕获不可访问文件夹的路径
【发布时间】:2020-12-30 10:53:45
【问题描述】:

我正在编写小脚本来捕获正在运行的系统上的文件哈希。我只有 Powershell 可用。

这是代码的活动部分:

get-childitem -path $path -filter $filename -Recurse -Force | Select FullName | foreach-object { get-filehash $_.fullname | select * }

这是我正在测试的命令:

./Get-FileHashesRecursive.ps1 -path c:\ -filename *.txt

运行脚本时,由于某些文件夹无法访问,我收到一系列错误。我想记录这些文件夹的路径,以便用户记录失败的完成情况。

控制台窗口中的错误如下所示:

get-childitem : Access to the path 'C:\$Recycle.Bin\S-1-5-21-4167544967-4010527683-3770225279-9182' is denied.
At E:\git\Get-RemoteFileHashesRecursive\Get-FileHashesRecursive.ps1:14 char:9
+         get-childitem -path $path -filter $filename -Recurse -Force | ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\$Recycle.Bin...3770225279-9182:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

有没有一种方法可以在不停止脚本其余部分运行的情况下获取路径或错误的整个第一行?

【问题讨论】:

  • 为什么不将-ErrorVariable FailedItems -ErrorAction SilentlyContinue 添加到您的Get-ChildItem 参数然后一旦您完成了您的命令,添加另一个类似这样的$FailedItems | Foreach-Object {$_.CategoryInfo.TargetName} | Out-File "C:\Users\sailingbikeruk\Desktop\noaccess.log"。希望你应该得到一个列出所有给出 UnauthorizedAccessException 错误的目录的文件
  • 在您的Get-ChildItem 命令中也包含-File 参数可能很有用!

标签: powershell error-handling get-childitem


【解决方案1】:

根据要求,这是我早期的 cmets 作为答案:

Get-ChildItem -Path $Path -Filter $Filename -File -Recurse -Force -ErrorVariable FailedItems -ErrorAction SilentlyContinue | ForEach-Object { Get-FileHash -Path $_.FullName | Select-Object * }
$FailedItems | Foreach-Object {$_.CategoryInfo.TargetName} | Out-File "C:\Users\sailingbikeruk\Desktop\noaccess.log"
  • 我已将-File 参数添加到Get-ChildItem,因为您专门处理的只是文件。
  • 我还在Get-ChildItem 命令中添加了-ErrorVariable-ErrorAction 参数。 -ErrorVariable FailedItems 为一个变量定义了一个自定义名称,该变量在处理过程中存储来自命令的错误。 -ErrorAction SilentlyContinue,告诉脚本继续而不通知您错误。
  • 一旦您的命令完成处理,您就可以解析$FailedItems 变量的内容。在上面的示例中,我将TargetName 输出到一个文件中,以便您可以在闲暇时阅读它,(请记住根据需要调整其文件路径和名称,如果您还希望将其输出到一个文件)。

【讨论】:

  • ErrorRecord 有一个成员 TargetObject 也存储路径。有理由偏爱CategoryInfo.TargetName吗?
  • 谢谢你,我会在周末测试这个,测试后将其标记为已回答。我不知道 -ErrorVariable 参数,它在未来可能会非常有用。
  • @zett42 您将如何访问 TargetObject,您能否扩展您的评论作为答案?
  • @Compo 对任何回复的延迟表示歉意。我已经尝试过您的解决方案,如果错误是“拒绝访问”,它会起作用,但如果错误是 The file <filename> cannot be read: The process cannot access the file <filename> because it is being used by another process,它似乎不会在 ErrorVariable 中创建条目。我不相信它会报告所有访问错误。
  • 这完全是另一个问题,十天后,没有接受您所说的答案,并且完全解决了所提出的问题,我不会发布另一个解决方案为您解决这一问题中的新问题。当我回答问题时,我不会注册成为您进一步问题的永久支持专家。请创建一个新问题(如果有),如果有,请记住,我们会帮助您修复您提供的代码的特定可重现问题,我们不会为您编写代码来添加您没有添加的新功能包括在内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2018-01-09
  • 2020-06-17
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
相关资源
最近更新 更多