Jaa


get-hashes.ps1: Get the hashes (sha256, md5, whatever) for a file

A slight modification of Mike's version, since sometimes I want md5, sometimes sha1, whatever, and I happen to like the '-' separators :)  I think sha256 makes a good default, though. 

The other differences are style related and just my personal preference:

  1. optimize for reading instead of writing (i've written and read enough perl in my life to know that it takes effort to make for readable scripts in such a language :)
  2. use scripts instead of functions so you can just add them to your script collection
  3. provide types for your arguments if you require them to be a specific type
  4. check that required arguments are passed

Admittedly, get-hashes is violating the rule of the nouns only being singular - I thought about just having the get-hashes.ps1 be get-hash, but I like the current flexibility that I can get just the hash (with no prefixing of text) or a list of hashes (more human readable).

get-hash.ps1:

 param(
    [string] $file = $(throw 'a filename is required'),
    [string] $algorithm = 'sha256'
)

$fileStream = [system.io.file]::openread((resolve-path $file))
$hasher = [System.Security.Cryptography.HashAlgorithm]::create($algorithm)
$hash = $hasher.ComputeHash($fileStream)
$fileStream.close()
$fileStream.dispose()

[system.bitconverter]::tostring($hash)

get-hashes.ps1:

 param(
    [string] $file = $(throw 'a filename is required'), 
    [string[]] $algorithms = ('mactripledes','md5','ripemd160','sha1','sha256','sha384','sha512')
)

foreach ($algorithm in $algorithms)
{
    "$algorithm hash for $file = $(hash $file $algorithm)"
} 

Admittedly, the output here is a little busy, and the default algorithms list is silly, but you get the point.

example output:

PS C:\> hashes StubInstaller.exe md5,sha1
md5 hash for StubInstaller.exe = E2-E6-B0-1D-43-C2-55-5B-1B-E3-F4-6D-82-97-D4-09
sha1 hash for StubInstaller.exe = 1C-34-BE-3D-A6-E0-F3-DD-64-A9-AA-6D-3A-EB-B4-0E-6A-7B-8B-93

PS C:\> hashes StubInstaller.exe
mactripledes hash for StubInstaller.exe = 21-C4-77-28-B0-7B-35-01
md5 hash for StubInstaller.exe = E2-E6-B0-1D-43-C2-55-5B-1B-E3-F4-6D-82-97-D4-09
ripemd160 hash for StubInstaller.exe = CF-E5-AD-54-8E-06-19-99-B0-98-89-64-1B-BC-63-52-36-13-20-E8
sha1 hash for StubInstaller.exe = 1C-34-BE-3D-A6-E0-F3-DD-64-A9-AA-6D-3A-EB-B4-0E-6A-7B-8B-93
sha256 hash for StubInstaller.exe = 75-7A-6C-47-61-2A-81-36-48-69-86-51-17-34-A1-EF-C0-48-87-F4-C5-B0-09-98-AF-A7-7A-E9-3D-F8-8B-B8
sha384 hash for StubInstaller.exe = DB-44-A4-B0-44-31-B8-FA-28-17-16-F7-0F-4F-AA-25-93-17-3D-BD-E8-05-7E-4C-05-6C-BE-3B-23-D5-DC-FC-BB-90-77-B5-93-23-77-40-0F-B4-CB-6F-64-9D-7A-6F
sha512 hash for StubInstaller.exe = 06-B3-F3-8B-6B-E0-8F-08-BC-9D-38-EF-36-7A-E4-4B-2A-AB-17-99-62-26-4E-F0-BA-1A-5E-54-94-8A-1C-40-33-79-60-EF-67-51-B5-28-41-EF-AE-4A-A4-97-15-61-0C-2A-BF-F5-93-83-DD-54-FB-88-DC-C5-73-ED-89-59