Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

md5 hashes in PowerShell (or CMD) with relative file paths

Tags:

powershell

cmd

I would like to write the md5 hashes for all files in a directory and its subdirectories to a file. Ideally, replicating the output of the unix command find . -type f -exec md5sum {} + (i.e. two columns: hashes and relative file paths).

I was looking at the CMD command CertUtil -hashfile afile.txt MD5 but I got stuck with the full file paths given by dir /A:-D /B /S. I found the following response using PowerShell: https://superuser.com/a/1249418. I've used CMD only rarely and this is my first attempt at 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

Is there a better way to get the hashes and relative paths in PowerShell (or CMD)? Or at least, can the intermediate file `temphashes.txt' be overwritten with the final output?

Edit: Can the hashes be made lowercase, and the headings and extra trailing blank lines be removed (see the second line in my attempt) so the file looks like:

d41d8ce98f00b204e9800988ecf8427e .\aSubDirectory\anotherfile.txt
4615fd7b904c04e94cbeced23361c778 .\afile.txt
like image 468
Stacey Avatar asked Jan 25 '26 15:01

Stacey


2 Answers

Does this get you what you're looking for?

$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

Explanation:

  • Retrieves all the files using Get-ChildItem in to a variable named $Files.
  • Loops through each file and uses Get-FileHash to retrieve the FileHash, which also returns the full path as path.
  • Pass this result to Select-Object and select just the Hash Property while using a Calculated Property to return Path as the relative path.
  • The results of the ForEach loop are returned to a $Result variable which is then output to a file with Out-File.
like image 149
Mark Wragg Avatar answered Jan 28 '26 05:01

Mark Wragg


Something like this:

Get-ChildItem -Path $path -Recurse | 
    Get-FileHash -Algorithm MD5 | 
    Select-Object "Hash","Path" | 
    ConvertTo-Csv -NoTypeInformation | 
    Out-File -FilePath "files.txt"
like image 25
mhu Avatar answered Jan 28 '26 04:01

mhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!