powershell - 具有相对文件路径的 PowerShell(或 CMD)中的 md5 哈希

标签 powershell cmd

我想将一个目录及其子目录中所有文件的 md5 哈希值写入一个文件。理想情况下,复制 unix 命令 find 的输出。 -type f -exec md5sum {} +(即两列:哈希值和相对文件路径)。

我正在查看 CMD 命令 CertUtil -hashfile afile.txt MD5 但我被 dir/A:-D/B/S 给出的完整文件路径卡住了。 我使用 PowerShell 发现以下响应:https://superuser.com/a/1249418 .我很少使用 CMD,这是我第一次尝试使用 PowerShell。

Get-FileHash -Algorithm MD5 -Path (Get-ChildItem "*.*" -Recurse | Resolve-Path -Relative | Tee-Object -Variable y) | select hash | Out-File C:\Users\MYUSERNAME\Desktop\MYFOLDER\temphashes.txt
$x = (Get-Content C:\Users\MYUSERNAME\Desktop\MYFOLDER\temphashes.txt).ToLower() | select -skip 3 | ?{$_.Trim(" `t")}
$i = 0; $x | ForEach-Object {($_, $y[$i]) -join " "; $i++} | Out-File C:\Users\MYUSERNAME\Desktop\MYFOLDER\hashes.txt

是否有更好的方法来获取 PowerShell(或 CMD)中的哈希值和相对路径?或者至少,中间文件“temphashes.txt”能否被最终输出覆盖?

编辑:是否可以将散列设为小写,并删除标题和多余的尾随空行(参见我尝试的第二行),以便文件看起来像:

d41d8ce98f00b204e9800988ecf8427e .\aSubDirectory\anotherfile.txt
4615fd7b904c04e94cbeced23361c778 .\afile.txt

最佳答案

这是否能满足您的需求?

$Files = Get-ChildItem "*.*" -Recurse

$Result = ForEach ($File in $Files) {
    Get-FileHash $File -Algorithm MD5 | Select-Object Hash,@{N='Path';E={$_.Path | Resolve-Path -Relative}}
} 

$Result | Out-File C:\Users\MYUSERNAME\Desktop\MYFOLDER\hashes.txt

解释:

  • 使用 Get-ChildItem 将所有文件检索到名为 $Files 的变量中。
  • 遍历每个文件并使用 Get-FileHash 检索 FileHash,它还会返回完整路径作为路径。
  • 将此结果传递给 Select-Object 并在使用 Calculated Property 时仅选择哈希属性返回 Path 作为相对路径。
  • ForEach 循环的结果返回到一个 $Result 变量,然后用 Out-File 输出到一个文件。

关于powershell - 具有相对文件路径的 PowerShell(或 CMD)中的 md5 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56426375/

相关文章:

windows - 使用 Findstr 返回上一行

javascript - 使用 JavaScript 创建在线 CMD/终端

powershell - 如何在PowerShell上使用ANSI编码实例化System.IO.StreamWriter?

powershell - 在 PowerShell 中合并数组中的对象

powershell - 获取传递给PowerShell中函数的所有参数

batch-file - 批量比较字符串

c# - 执行后如何保持控制台窗口打开?

string - 如何使用CMD拆分字符串

powershell - 如何将 get-childitem 的结果传递到命令中?

visual-studio - 是否可以在 Developer Powershell 终端中更改字体?