PowerShell Cmdlet Spotlight: Get-FileHash
Welcome back to Wahman’s PowerShell Blog! Today we’re going to take a closer look at an incredibly useful cmdlet: Get-FileHash. According to the Microsoft documentation:
Computes the hash value for a file by using a specified hash algorithm.
This cmdlet is a powerful tool when it comes to verifying file integrity, ensuring files haven’t been tampered with, and in general scripting scenarios where you want to compare file contents using hashes. The default algorithm is SHA256, but others such as MD5 and SHA1 can also be used.
Beginner Example: Generate the SHA256 hash of a single file
If you just want to get the hash of a file, it’s extremely simple:
Get-FileHash -Path "C:\Users\YourName\Documents\example.zip"
This will output a hash value calculated using the SHA256 algorithm by default. This is perfect for checking if a download matches a known good hash.
Intermediate Example: Generate an MD5 hash
Sometimes, a file’s authenticity is verified with an MD5 hash. You can easily specify a different algorithm:
Get-FileHash -Path "C:\Users\YourName\Documents\example.zip" -Algorithm MD5
While MD5 is not considered cryptographically secure anymore, it’s still widely used for basic file checksums.
Advanced Example: Compare two files for equality using their hash
Let’s say you want to check whether two files are identical, regardless of their names or locations:
$hash1 = Get-FileHash -Path "C:\Temp\file1.txt"
$hash2 = Get-FileHash -Path "C:\Backup\file1_backup.txt"
if ($hash1.Hash -eq $hash2.Hash) {
Write-Output "Files are identical."
} else {
Write-Output "Files differ."
}
This is super helpful for verifying whether your backup routines are capturing the correct files.
Advanced Scripting Example: Verify integrity of a large directory
Want to generate hash values for a whole directory and save them for later verification? Here’s a quick script to do just that:
$directory = "C:\ImportantData"
$outputFile = "C:\Hashes\file_hashes.csv"
Get-ChildItem -Path $directory -Recurse -File |
ForEach-Object {
Get-FileHash -Path $_.FullName | Select-Object Path, Hash, Algorithm
} | Export-Csv -Path $outputFile -NoTypeInformation
This will walk through all files in C:\ImportantData, compute the hash, and output it to a CSV for later validation.
This cmdlet is simple yet powerful, and whether you’re scripting for backups, integrity checking, or compliance, Get-FileHash is a tool worth mastering.
Happy scripting, and I will see you in the next post!
Leave a Reply