gpt4 book ai didi

powershell - 如何在 Powershell 的文件名中计算和插入 SHA?

转载 作者:行者123 更新时间:2023-12-02 22:35:51 25 4
gpt4 key购买 nike

我希望通过 SHA 值计算和过滤文件以查找重复文件。我有超过 6000 个图像文件,我希望在一个文件夹中对其执行此操作。

我想计算并将文件的 SHA 值插入到文件名中。

这就是我正在尝试的:

 get-childitem * rename-item -NewName {$_.Name -replace '*' '*'+ Get-FileHash *./}

+ 是我希望添加 SHA 值的地方。这是文件名和我得到的错误。 https://imgur.com/a/FJ8v0SG

最佳答案

$_ 指的是 -NewName block 中的当前文件,这是计算哈希所需的一切:

Get-ChildItem -Path C:\Folder\With\Files\ -File | Rename-Item -NewName {
# pipe current file to Get-FileHash, grab resulting hash string
$hash = $_ |Get-FileHash -Algorithm SHA1 |Select -Expand Hash
# rename from `basename.ext` to `basename_SHA1HASH.ext`
$_.BaseName + '_' + $hash + $_.Extension
}

话虽这么说,如果您试图识别同一文件夹(或文件夹层次结构)中的重复项,则无需重命名文件,您可以在内存中对生成的哈希值进行分组,并以这种方式过滤重复项:

# Create dictionary to keep track of Hash->FilePath(s) relation:
$FilesBySHA1Sum = @{}

# Enumerate all files
Get-ChildItem -Path C:\folder\with\target\files -File |ForEach-Object {
# Calculate individual file hash
$SHA1Sum = $_ |Get-FileHash -Algorithm SHA1

if($SHA1Sum){
# Add result to hash table
$FilesBySHA1Sum[$SHA1Sum.Hash] += @($SHA1Sum.Path)
}
}

# Figure out which entries in the hash table has more than one path
$Duplicates = $FilesBySHA1Sum.GetEnumerator() |Where-Object {$_.Value.Count -gt 1}

$Duplicates 现在是重复哈希和关联文件路径的列表。

您可以使用 Get-ChildItem |Group-Object { $_ |Get-FileHash |Select -Expand Hash } 实现相同或相似的效果,但是 Group-Object在跟踪输入元素时,Windows PowerShell 中的速度呈指数级下降,因此可能不是一次分析多个文件的最佳选择。

关于powershell - 如何在 Powershell 的文件名中计算和插入 SHA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63538391/

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