Reputation: 1505
I am trying to make a script that can get the hash MD5 of Files and Directories that I get with the function ChildItem. My Script at the moment is the following. Why is the part of the Hash not working?
$UserInput = Read-Host
Get-ChildItem -Path $UserInput -Recurse
function md5hash($UserInput)
{
$fullPath = Resolve-Path $UserInput
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
[System.BitConverter]::ToString($md5.ComputeHash($file))
$file.Dispose()
}
Upvotes: 1
Views: 9716
Reputation: 1377
As a one-liner:
Get-ChildItem -Path C:\Temp -Recurse -File | Get-Filehash -Algorithm MD5
Upvotes: 2
Reputation: 2935
$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
Edit: Your code should work fine and even better than what I proposed as my example is limited to files < 2GB in size. Since yours uses a Stream, it's more efficient (doesn't load it all into memory first), and won't have the size limitation.
Your file path must be a file since you're making I/O calls specific to files...
Upvotes: 1