【发布时间】: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