-1

Hi just wondering if anybody can help me out? I have piece of code to workout the Sha-1 of a folder but need to convert it to get the sha-256.

function Get-FolderHash ($folder) {
 dir $folder -Recurse | ?{!$_.psiscontainer} | %{[Byte[]]$contents += [System.IO.File]::ReadAllBytes($_.fullname)}
 $hasher = [System.Security.Cryptography.SHA1]::Create()
 [string]::Join("",$($hasher.ComputeHash($contents) | %{"{0:x2}" -f $_}))
}

Get-FolderHash out

I also need to get the equivalent in 2 other programming languages if anyone has any tips. Thank you

1 Answers1

1

A few thoughts:

  • A lot of this is natively available in PowerShell (e.g. using Get-FileHash)
  • I suggest not using the 'short form' for language constructs - i.e. use where instead of ? and foreach instead of %. The PSScriptAnalyzer is even more strict and recommends the more verbose Where-Object form, that's an option too.

You can specify SHA-256 as the algorithm to Get-FileHash.

Here's an example that covers the points above in PowerShell

function Get-FolderHash ($folder) {
  Get-ChildItem $folder -Recurse | Where {!$_.PSIsContainer} | ForEach {
    Get-FileHash -Algorithm SHA256 "$($_.FullName)" | Select Hash, Path
  }
}

This will output a table showing the computed hash and the path.

I'll leave others more familiar with Python & Java to help there.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Stu
  • 153
  • 9
  • Nice. "short forms" are [aliases](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Aliases). While it's true that they're best avoided in _scripts_ - as opposed to _interactive_ usage - in script's they're realistically only a problem if they're not _built-in_ aliases (leaving readability aside). – mklement0 Nov 22 '20 at 23:24
  • 1
    * _in scripts_. Also note that pure expressions such as `$_.FullName` need not be enclosed in `"$(...)`", and that in _PowerShell [Core] v6.1+_ even `$_` by itself can be _always_ be relied on to evaluate to the full path with `Get-ChildItem` / `Get-Item` input - see [this answer](https://stackoverflow.com/a/53400031/45375), and [this answer](https://stackoverflow.com/a/41254359/45375) for how PowerShell generally parses _unquoted_ command arguments. – mklement0 Nov 23 '20 at 01:44