Overview
The Get-FileHash command in PowerShell enables you to calculate the hash value of a file using a specific hash algorithm. A hash value is a unique identifier that corresponds to the file’s content. Unlike relying solely on the file name or extension, a hash offers a secure way to identify a file’s content. Even if a file’s name, extension, or content changes slightly, the hash value will differ.
Hash values serve the purpose of ensuring the integrity of a file, meaning that no unauthorized or accidental changes have been made to its content. Furthermore, hash values can also be used to determine if two files have exactly the same content. If their hash values are identical, then the files are identical too.
By default, the Get-FileHash command employs the SHA256 algorithm. However, you can use any hash algorithm supported by your operating system.
Examples
Example 1: Calculate the hash value for a file
To calculate the hash value for the /etc/apt/sources.list
file using the default SHA256 algorithm, execute the following command:
Get-FileHash /etc/apt/sources.list | Format-List
Example 2: Calculate the hash value for an ISO file
Suppose you want to calculate the hash value for the ISO file C:Usersuser1DownloadsContoso8_1_ENT.iso
using the SHA384 algorithm. Use the following command:
Get-FileHash C:Usersuser1DownloadsContoso8_1_ENT.iso -Algorithm SHA384 | Format-List
Example 3: Calculate the hash value of a stream
In this example, we are downloading a package from the PowerShell release page using the System.Net.WebClient
class. The release page provides the SHA256 hash for each package file. We can compare the published hash with the one we calculate using Get-FileHash:
$wc = [System.Net.WebClient]::new()
$pkgurl = 'https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell_6.2.4-1.debian.9_amd64.deb'
$publishedHash = '8E28E54D601F0751922DE24632C1E716B4684876255CF82304A9B19E89A9CCAC'
$FileHash = Get-FileHash -InputStream ($wc.OpenRead($pkgurl))
$FileHash.Hash -eq $publishedHash # Outputs 'True'
Example 4: Calculate the hash of a string
Although PowerShell does not provide a built-in cmdlet to compute the hash of a string directly, you can achieve it using the InputStream
parameter of Get-FileHash. Here’s an example:
$stringAsStream = [System.IO.MemoryStream]::new()
$writer = [System.IO.StreamWriter]::new($stringAsStream)
$writer.write("Hello world")
$writer.Flush()
$stringAsStream.Position = 0
Get-FileHash -InputStream $stringAsStream | Select-Object Hash
Parameters
- -Algorithm
- -InputStream
- -LiteralPath
- -Path
Inputs
- String
You can provide a string containing the file path to this cmdlet.
Outputs
- Microsoft.PowerShell.Utility.FileHash
This cmdlet generates an object that represents the specified file’s path, the computed hash value, and the used hash algorithm.