I have been attempting to replicate the output of the Unix command find . -type f -exec md5sum {} +
to compute hashes for all files in a directory and its subdirectories in PowerShell (i.e. two columns: MD5 hashes in lowercase and relative file paths). Is there a better way to have newlines marked with a line feed instead of a carriage return and a line feed than in the following code?
$Result = Get-FileHash -Algorithm MD5 -Path (Get-ChildItem "*.*" -Recurse) | Select-Object @{N='Hash';E={$_.Hash.ToLower()}},@{N='Path';E={$_.Path | Resolve-Path -Relative}}
($Result | Format-Table -AutoSize -HideTableHeaders | Out-String).Trim() + "`n" -replace ' *\r\n',"`n" | Set-Content -NoNewline -Encoding ascii $ENV:USERPROFILE\Desktop\MYFOLDER\hashes.txt
The first line returns the hashes in lowercase and the relative paths.
The second line uses Format-Table
to exclude the column headings (with the option -HideTableHeaders
plus it uses the option -AutoSize
to avoid truncating long relative file paths).
Out-String
converts the output to a string and .Trim()
removes the preceding and trailing blank lines.
Presently, I add a line feed
`+ "`n"`
then use
`-replace ' *\r\n',"`n"`
to do the replacement and eliminate any extra spaces at the end of each line. Finally, Set-Content
uses the option -NoNewline
to avoid a newline with a carriage return.
I've seen these similar questions: Replace CRLF using powershell and In PowerShell how to replace carriage return