Before the advent of PowerShell 5 (and Get-FileHash), to calculate hashes for strings and files, you’d need to resort to pure .NET methods. Here is sample code to create a MD5 hash for a string:
$Text = 'this is the text that you want to convert into a hash' $Provider = New-Object -TypeName Security.Cryptography.MD5CryptoServiceProvider $Encodiner = New-Object -TypeName Text.UTF8Encoding $Bytes = $Encodiner.GetBytes($Text) $hashBytes = $Provider.ComputeHash($Bytes) $hash = [System.BitConverter]::ToString($hashBytes) # remove dashes if needed $hash -replace '-'
If you’d like to calculate a hash for a file content, either use Get-Content to read the file, or try this:
$Path = "C:\somefile.txt" # use your current PowerShell host as a sample $Path = Get-Process -Id $Pid | Select-Object -ExpandProperty Path $Provider = New-Object -TypeName Security.Cryptography.MD5CryptoServiceProvider $FileContent = [System.IO.File]::ReadAllBytes($Path) $hashBytes = $Provider.ComputeHash($FileContent) $hash = [System.BitConverter]::ToString($HashBytes) $hash -replace '-'
psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!