如何在 PowerShell 中获取 MD5 校验和 [英] How to get an MD5 checksum in PowerShell

查看:38
本文介绍了如何在 PowerShell 中获取 MD5 校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一些内容的 MD5 校验和.如何在 PowerShell 中执行此操作?

I would like to calculate an MD5 checksum of some content. How do I do this in PowerShell?

推荐答案

如果内容是字符串:

$someString = "Hello, World!"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = New-Object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))

如果内容是文件:

$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))

<小时>

从 PowerShell 版本 4 开始,这对于使用 Get-FileHash cmdlet:


Starting in PowerShell version 4, this is easy to do for files out of the box with the Get-FileHash cmdlet:

Get-FileHash <filepath> -Algorithm MD5

这当然更可取,因为它避免了第一个解决方案在注释中指出的问题(使用流、关闭它并支持大文件).

This is certainly preferable since it avoids the problems the first solution offers as identified in the comments (uses a stream, closes it, and supports large files).

这篇关于如何在 PowerShell 中获取 MD5 校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆