如何直接将 Get-FileHash
的输出与 Properties.ContentMD5
的输出进行比较?
我正在编写一个 PowerShell 脚本,该脚本从我的系统中获取一些本地文件并将它们复制到 Azure Blob 存储容器。
文件每天都会发生变化,因此我在上传之前添加了检查以查看文件是否已存在于容器中。
我使用Get-FileHash
读取本地文件:
$LocalFileHash = (Get-FileHash "D:\file.zip" -Algorithm MD5).Hash
这导致 $LocalFileHash
持有以下内容:67BF2B6A3E6657054B4B86E137A12382
我使用此代码来获取已传输到容器的 blob 文件的校验和:
$BlobFile = "Path\To\file.zip"
$AZContext = New-AZStorageContext -StorageAccountName $StorageAccountName -SASToken "<token here>"
$RemoteBlobFile = Get-AzStorageBlob -Container $ContainerName -Context $AZContext -Blob $BlobFile -ErrorAction Ignore
if ($ExistingBlobFile) {
$cloudblob = [Microsoft.Azure.Storage.Blob.CloudBlockBlob]$RemoteBlobFile.ICloudBlob
$RemoteBlobHash = $cloudblob.Properties.ContentMD5
}
$RemoteBlobHash
的值设置为 Z78raj5mVwVLS4bhN6Ejgg==
没问题,我想,我只需解密 Base64 字符串并进行比较:
$output = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($RemoteBlobHash))
这给了我g�+j>fWKK��7�#�
所以不能直接比较☹
This question显示某人处于类似的 pickle 中,但鉴于其本地 MD5 结果的格式,我认为他们没有使用 Get-FileHash
。
我尝试过的其他事情:
- 将
UTF8
上方的 System.Text.Encoding 行更改为 UTF16 和 ASCII,这会更改输出,但不会更改为任何可识别的内容。 - 尝试使用 GetBytes 看看是否有帮助:
$output = [System.Text.Encoding]::UTF8.GetBytes([System.Text.Encoding]::UTF16.GetString([System.Convert]::FromBase64String($RemoteBlobHash)))
注意:使用 md5sum 比较本地文件和下载的 file.zip 副本会产生与 Get-FileHash
相同的 MD5 字符串:67BF2B6A3E6657054B4B86E137A12382
提前谢谢您!
最佳答案
ContentMD5
是二进制哈希值的 Base64 表示,而不是生成的十六进制字符串:)
$md5sum = [convert]::FromBase64String('Z78raj5mVwVLS4bhN6Ejgg==')
$hdhash = [BitConverter]::ToString($md5sum).Replace('-','')
这里我们转换base64 -> 二进制 -> 十六进制
如果您需要以相反的方式执行此操作(即,获取本地文件哈希,然后使用它在 Azure 中搜索 blob),您首先需要将十六进制字符串拆分为字节大小的 block ,然后将生成的字节数组转换为 base64:
$hdhash = '67BF2B6A3E6657054B4B86E137A12382'
$bytes = [byte[]]::new($hdhash.Length / 2)
for($i = 0; $i -lt $bytes.Length; $i++){
$offset = $i * 2
$bytes[$i] = [convert]::ToByte($hdhash.Substring($offset,2), 16)
}
$md5sum = [convert]::ToBase64String($bytes)
关于powershell - 比较 Azure Properties.ContentMD5 和 Get-Filehash 之间的字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61895997/