命令行管理程序 - 将命令输出设置为变量并替换



我正在开发一个PowerShell脚本来计算zip文件的校验和。我必须在 W7 和 W10 中执行它。我注意到 certUtil commmand 返回像 A2 5B 8A 这样的字符串......在 W7 中,但在 W10 中,它返回相同的字符串但没有空格。所以我决定删除空格以统一它,将输出设置为变量,然后删除空格......但它不起作用。

for /f  "delims=" %%f in ('dir %~dp0*.zip /b') do (
echo %%~f:
$result = certUtil -hashfile "%~dp0%%~f" SHA512 | find /i /v "SHA512" | 
find /i /v "certUtil"
$result = $result -replace 's', ''
echo %result%
set /a counter += 1
echo.
)

你知道如何删除它们吗?

所以在你的例子中,你似乎正在使用 Shell 命令,如 For、Echo、Set 然后你混合了像 $ 这样的 powershell 命令

你应该使用所有的powershell,因为你说你正在处理一个powershell脚本。

Get-ChildItem "C:TEST" -Include *.zip -File -Recurse | %{
Get-FileHash $_ -Algorithm SHA512 | select Path, Hash
}

这会在测试中获取所有 zip 文件,然后使用 Get-Filehash,然后使用 Sha512 算法。返回文件和哈希的路径。

这至少需要Powershell 4.0

对于在7 和 10(分别为版本 2 和 5(上与内置 powershell 版本一起使用的解决方案,我会坚持使用certutil.

certutil -hashfile的输出的第二行包含哈希,所以像这样抓取它:

Get-ChildItem -Filter *.zip -Recurse |ForEach-Object {
# call certutil, grab second line of output (index 1)
$hashString = @(certutil -hashfile """$($_.FullName)""" SHA512)[1]
# remove any non-word characters from the output:
[regex]::Replace($hashString,'[W]','')
}

最新更新