gpt4 book ai didi

powershell - 在PowerShell中捕获错误并处理被阻止的文件

转载 作者:行者123 更新时间:2023-12-03 07:42:42 24 4
gpt4 key购买 nike

这个问题的历史在于我问过的更早的问题here
我正在运行此命令以获取给定位置中所有文件的文件散列,但是我需要捕获所有丢失或无法访问的文件。

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"
在前面的问题中,我认为我只需要捕获文件夹,给出和接受的答案确实捕获了所有拒绝文件夹访问的消息,但是该命令没有捕获无法访问的单个文件。建议的答案(使用-errorvariable)似乎没有记录这些路径。
我不清楚为什么-ErrorVariable从此错误中捕获路径:
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
但不是这个
Get-FileHash : The file 'E:\devices.csv' cannot be read: The process cannot access the file
'E:\devices.csv' because it is being used by another process.
At E:\Scripts\Ian\git\Get-RemoteFileHashesRecursive\Get-FileHashesRecursive.ps1:25 char:132
+ ... FailedItems | ForEach-Object { Get-FileHash -Path $_.FullName | Selec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (E:\devices.csv:PSObject) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : FileReadError,Get-FileHash
在此示例中,我将 $_.CategoryInfo.TargetName写入错误日志,但我也尝试编写 $_.TargetObject并获得相同的结果

最佳答案

公用参数-ErrorVariable-ErrorAction仅适用于单个命令。因此,您也必须将它们添加到Get-FileHash中:

Get-ChildItem -Path $Path -Filter $Filename -File -Recurse -Force -ErrorVariable FailedItems -ErrorAction SilentlyContinue | 
ForEach-Object {
Get-FileHash -Path $_.FullName -ErrorVariable +FailedItems -ErrorAction SilentlyContinue | Select-Object *
}

$FailedItems | Foreach-Object {$_.CategoryInfo.TargetName} | Out-File "C:\Users\sailingbikeruk\Desktop\noaccess.log"
请注意,我已经在 +的错误变量名称之前插入了 Get-FileHash,以防止其清除 Get-ChildItem产生的任何错误。参见 about_CommonParameters
不相关的改进:
您可以删除 ForEach-Object并将其直接通过管道传递到 Get-ChildItem中。 Get-FileHash也是多余的。
Get-ChildItem -Path $Path -Filter $Filename -File -Recurse -Force -ErrorVariable FailedItems -ErrorAction SilentlyContinue | 
Get-FileHash -ErrorVariable +FailedItems -ErrorAction SilentlyContinue

关于powershell - 在PowerShell中捕获错误并处理被阻止的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65734378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com