HiveBrain v1.2.0
Get Started
← Back to all entries
patternshellMinor

Powershell function to get hash value of a file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filepowershellfunctionvaluehashget

Problem

I created a function to get the hash value of a file. Normally the output is 3 lines. My function does 3 things:

  • extracts the hash value



  • removes the spaces in between the hash value



  • prints hash value



Here is the output when using CertUtil -hashfile FILENAME.EXE SHA1

SHA1 hash of file FILENAME.EXE:
XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
CertUtil: -hashfile command completed successfully.


My function:

function MyHash($file, $hashtype) {
    $hash = CertUtil -hashfile $file $hashtype
    $hashstring = $hash[1] -replace ' ',''
    echo $hashstring
}


my output:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


Am I ok calling commands such as CertUtil from within a function the way I am doing? Can the syntax and code be improved? I feel like I'm just throwing commands inside a function but it works.

Solution

I think your code is okay. Some notes:

  • PowerShell 4 has a Get-FileHash command. Granted, most people don't have PS4 yet.



  • Why reinvent the wheel when other people have already done it better? E.g.: Boe Prox's Get-FileHash.



  • I believe the PowerShell Community Extensions also have a file hash command.



  • The dependency on certutil is not ideal. Do we know that the output format from all versions of certutil will be same everywhere and for all time?



  • You don't need the echo in the last line. The last line can consist of just $hashstring by itself. Since that value is not being consumed, it will be placed in the pipeline. (It's important, by the way, to understand how the pipeline works to use PowerShell.)

Context

StackExchange Code Review Q#106163, answer score: 4

Revisions (0)

No revisions yet.