Created
May 14, 2024 13:59
-
-
Save MyITGuy/ace2e2fb16eeb55a1a36fe0bd7231ed5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-DirectoryHash { | |
[CmdletBinding()] | |
param( | |
[System.IO.DirectoryInfo] | |
$Path | |
, | |
[switch] | |
$IncludeName | |
) | |
begin { | |
function Get-StringHash { | |
[CmdletBinding()] | |
PARAM( | |
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] | |
[AllowNull()] | |
[AllowEmptyString()] | |
[String]$String | |
, | |
[Parameter(Position = 1, Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] | |
[ValidateSet('SHA', 'SHA1', 'System.Security.Cryptography.SHA1', 'System.Security.Cryptography.HashAlgorithm', 'MD5', 'System.Security.Cryptography.MD5', 'SHA256', 'SHA-256', 'System.Security.Cryptography.SHA256', 'SHA384', 'SHA-384', 'System.Security.Cryptography.SHA384', 'SHA512', 'SHA-512', 'System.Security.Cryptography.SHA512')] | |
[String]$HashName = "MD5" | |
) | |
begin { | |
$StringBuilder = New-Object System.Text.StringBuilder | |
} | |
process { | |
if ($String.Trim().Length) { | |
[System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) | ForEach-Object { | |
[Void]$StringBuilder.Append($_.ToString("x2")) | |
} | |
$StringBuilder.ToString() | |
} | |
} | |
end { | |
} | |
} | |
} | |
process { | |
$Items = Get-ChildItem -Path $Path -File -Recurse | ForEach-Object { | |
$Item = $_ | |
$Item | Add-Member -MemberType ScriptProperty -Name RelativePath -Value { ($this.DirectoryName -replace "^$([regex]::Escape($Path))", '\') -replace '\\', '\' } -Force | |
$Item | Add-Member -MemberType ScriptProperty -Name MD5Hash -Value { Get-FileHash -Path $this.FullName -Algorithm MD5 | Select-Object -ExpandProperty Hash } -Force | |
$Item | Add-Member -MemberType ScriptProperty -Name MD5FileName -Value { "$($this.MD5Hash)_$($this.Name)" } -Force | |
$Item | Add-Member -MemberType ScriptProperty -Name MD5RelativePath -Value { Join-Path -Path $this.RelativePath -ChildPath $this.MD5Hash } -Force | |
$Item | Add-Member -MemberType ScriptProperty -Name MD5RelativeUniquePath -Value { Join-Path -Path $this.RelativePath -ChildPath $this.MD5FileName } -Force | |
$Item | |
} | Sort-Object -Property FullName | |
if ($IncludeName) { | |
$StringToHash = $Items.MD5RelativeUniquePath | Out-String | |
} else { | |
$StringToHash = $Items.MD5RelativePath | Out-String | |
} | |
Get-StringHash -String $StringToHash -HashName MD5 | |
} | |
end { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment