Powershell 的哈希方法

Powershell 的哈希方法

最近写脚本需要用到文件与内容哈希, 在这里作下速记.

文件哈希 与 字符哈徐

pwsh 原生支持文件哈希 Get-FileHash, 但是字符哈希需要手动调用 C# 模块 :

  1. UTF8Encoding: 将文本转换为字节数组
  2. MD5: 加密字节数组
  3. BitConverter: 将字节数组转为字符串

简单的用例

以下命令在临时文件夹生成临时文件并写入 $PSHOME 属性

1
2
3
4
5
6
7
8
9
10
11

sl $env:TMP
$fn = "$(New-Guid).txt"
$PSHOME |Set-Content -LiteralPath "$fn" -NoNewline
Get-FileHash -Algorithm MD5 -Path $fn | Select-Object -ExpandProperty 'Hash' | Tee-Object -Variable hashOfCmd
Invoke-Item $fn -whatIf
[System.Text.UTF8Encoding]::UTF8.GetBytes((Get-Content '4c4b6320-7937-467c-8d25-a55a3835aa03.txt')) | Set-Variable bits
[System.Security.Cryptography.MD5]::Create().ComputeHash($bits)| Set-Variable hash
[System.BitConverter]::ToString($hash).Replace('-','') | Tee-Object -Variable hashOfMethod
$hashOfCmd -eq $hashOfMethod

  1. pwsh 运行时自动加载目录下的 dll , 可通过 Invoke-Item $PSHOME 确认
  2. pwsh 运行时加载的 dll , 可通过 [Threading.Thread]::GetDomain().GetAssemblies() 确认