Powershell 2: Optimal way to compute checksum on file?

I run a script to process a CSV file once an hour. At the beginning of the script, I need to exit out if the CSV file has not changed. Let's pretend that file timestamps aren't an option. (I'm asking this question for educational value)

I was considering slurping in the entire file and computing the hash on the contents, like so:

$fileData = get-content \path\to\file
$hashCode = $fileData.GetHashCode()

I would then save those contents from run to run, and if the hash is the same on subsequent runs, exit out of my script.

Is there a better way to do this, again, assuming file timestamps are not available?


Solution 1:

You'll end up using the System.Security.Cryptography namespace to generate that hash. The PowerShell Community Extensions have already done the work for you. There is a Get-Hash cmdlet that returns a HashInfo object you could use for your comparison.

Solution 2:

One thing to note, the Get-HashCode() is not meant to be used as a unique object identifier. It will always be different every time you run it, even in the same session.

Check here and here for more information.