Sometimes you need to create a file checksum to make sure files are not tampered with. Luckily PowerShell offers a standard cmdlet for this: Get-FileHash. Use this to validate file integrity in Windows (Windows Server).

Identifying changed files and possible attacks on your systems is of create importance. PowerShell offers the Get-FileHash cmdlet which computes a hash value of a file. If a hash value has changed a file has change and might indicate a possible infection or attack. Here is how to use Get-FileHash.

The cmdlet Get-FileHash:

... computes the hash value for a file by using a specified hash algorithm. A hash value is a unique value that corresponds to the content of the file.

As long as there are no collisions likely (we all remember MD5 collisions), a hash algorithm can be a valuable method in your day to day security and systems administration workflow: Checking files haven't been tampered with.

Suppose I have a file cmd.exe (yeah we all know that one :-) ). Its hash value is:

Get-FileHash C:\Windows\System32\cmd.exe | Select-Object Hash

Hash
----
423E0E810A69AACEBA0E5670E58AFF898CF0EBFFAB99CCB46EBB3464C3D2FACB

Or in one command:

(Get-FileHash C:\Windows\System32\cmd.exe).Hash
423E0E810A69AACEBA0E5670E58AFF898CF0EBFFAB99CCB46EBB3464C3D2FACB

If I copy that executable to my local directory, the file hash remains the same:

PS C:\Users\Jan Reilink> copy C:\Windows\System32\cmd.exe .
PS C:\Users\Jan Reilink> (Get-FileHash "C:\Users\Jan Reilink\cmd.exe").Hash
423E0E810A69AACEBA0E5670E58AFF898CF0EBFFAB99CCB46EBB3464C3D2FACB

But as soon as I echo (append) a whitespace into the executable file, its file hash changes:

PS C:\Users\Jan Reilink> echo " " >> "C:\Users\Jan Reilink\cmd.exe"
PS C:\Users\Jan Reilink> (Get-FileHash "C:\Users\Jan Reilink\cmd.exe").Hash
B01356E4439C05727982FDB62D2F49B04A23F39CA63BF2076EEB022E4B914760

If I were to regularly store and check / verify file checksums, I now know the file is tampered with. Such file changes might indicate an attack. File Integrity Monitor (FIM) in Windows Defender for Cloud can also do this for you.

Learn working with file attributes in PowerShell to verify the LastWriteTime (or last modified date) time of files.

Did you know you can also use certutil.exe for the job? Even for checking an MD5 checksum? See:

PS C:\Users\Jan Reilink> certutil.exe -hashfile C:\Windows\System32\cmd.exe SHA256
SHA256 hash of C:\Windows\System32\cmd.exe:
423e0e810a69aaceba0e5670e58aff898cf0ebffab99ccb46ebb3464c3d2facb
CertUtil: -hashfile command completed successfully.
PS C:\Users\Jan Reilink> certutil.exe -hashfile C:\Windows\System32\cmd.exe MD5
MD5 hash of C:\Windows\System32\cmd.exe:
5a6be4d2519515241d0c133a26cf62c0
CertUtil: -hashfile command completed successfully.
Donate a cup of coffee
Donate a cup of coffee

Thank you very much! <3 ❤️

2 Comments

Comments are closed