Using Powershell for File Integrity

Powershell uses the Get-FileHash cmdlet to generate a unique hash for a given file:

PS C:\> Get-FileHash .\test.txt

Algorithm      Hash                                  Path
---------      ----                                  ----
SHA256         59A82547CAC1A8A35EBB254F66B3C4...     C:\test.txt

A hash is useful when you need to verify the integrity of a file. To check the integrity of your system, you can create a baseline of file hashes, and periodically check for changes against the baseline.  Powershell makes checking the integrity of multiple files very easy by combining Get-ChildItem (or dir/ls) with Get-Filehash.

PS C:\test> Get-ChildItem | Get-FileHash

Algorithm      Hash                                 Path
---------      ----                                 ----
SHA256         BA7816BF8F01CFEA414140DE5DAE22...    C:\test\file_1.txt
SHA256         A665A45920422F9D417E4867EFDC4F...    C:\test\file_2.txt

Knowing this, it is very easy to create a baseline of system file hashes by using the parameter -Recurse, which will recurse the file system and take the hashes of any files within sub-folders. The results can be outputted to a file for a baseline:

PS C:\test> Get-ChildItem -Recurse | Get-FileHash | Export-Csv -Path C:\results\baseline_hashes.csv

If I make a change to file_1.txt, when I run the command again the output of the hash will be different. Ideally, we would want to compare the hashes when the script is run against the baseline, and report any changes. Powershell can compare output using the Compare-Objects cmdlet: (all one command)

PS C:\test> Compare-Object (Get-Content C:\results\baseline_hashes.csv)(Get-Content C:\results\current_hashes.csv) | Format-Table -Wrap | Out-File C:\results\differences_hashes.txt

If there are no differences between the baseline and the current, then a blank text file would be produced. If the file is blank, you wouldn’t need to know about it, otherwise, you would want to be notified. To check if the file is blank you could use Powershell to read the file, and if it is blank, exit the script.

If ((Get-Content "differences_hashes.txt") -eq $Null) {
                "File is blank"
                exit
}

If the file shows differences, you could script an action that would alert an administrator, such as sending an email or sms alert.

Leave a Reply

Your email address will not be published. Required fields are marked *