我想从Windows CMD在PowerShell中执行一个功能。基本上,要求是计算字符串的哈希,因为Windows batch / cmd不提供生成字符串的哈希的功能,所以我必须使用PowerShell。
我不想运行PowerShell脚本或将功能放在ps脚本中,因为这样做,我不得不绕过Windows PowerShell安全策略。
下面是我在Hash.cmd
中运行的代码。在PowerShell中执行时,该代码运行良好。
@echo off
powershell -Command "& { Function Get-Hash([String] $String) { $StringBuilder = New-Object System.Text.StringBuilder; [System.Security.Cryptography.HashAlgorithm]::Create("sha1").ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{ [Void]$StringBuilder.Append($_.ToString("x2")); }; $StringBuilder.ToString(); }; $res=Get-Hash "Hello world"; echo $res; }"
但这会导致CMD错误,如下所示:
At line:1 char:153 + ... lder; [System.Security.Cryptography.HashAlgorithm]::Create(sha1).Co ... + ~ Missing ')' in method call. At line:1 char:153 + ... ; [System.Security.Cryptography.HashAlgorithm]::Create(sha1).Comput ... + ~~~~ Unexpected token 'sha1' in expression or statement. At line:1 char:41 + & { Function Get-Hash([String] $String) { $StringBuilder = New-Object ... + ~ Missing closing '}' in statement block or type definition. At line:1 char:3 + & { Function Get-Hash([String] $String) { $StringBuilder = New-Object ... + ~ Missing closing '}' in statement block or type definition. At line:1 char:157 + ... [System.Security.Cryptography.HashAlgorithm]::Create(sha1).Compute ... + ~ Unexpected token ')' in expression or statement. At line:1 char:262 + ... etBytes($String))|{ [Void]$StringBuilder.Append($_.ToString(x2)); }; ... + ~ Missing ')' in method call. At line:1 char:262 ---- TRUNCATED-----
答案 0 :(得分:4)
您遇到了报价问题,因为您在双引号中使用了双引号,这会破坏报价。
由于代码中双引号的字符串不需要扩展(请参见about_quoting_rules),因此只需更改双引号"sha1"
/ "x2"
/ {{1} }改为单引号,例如"Hello world"
编辑:为我工作的代码:
'sha1'
答案 1 :(得分:0)
问题是我在Foreach-Object中使用了%
下面是正确的cmd脚本
@echo off
powershell -command "& { Function Get-Hash([String] $String) { $StringBuilder = New-Object System.Text.StringBuilder; [System.Security.Cryptography.HashAlgorithm]::Create('sha1').ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) | Foreach-object { [Void]$StringBuilder.Append($_.ToString('x2')); }; $StringBuilder.ToString(); }; $hash=Get-Hash 'Hello World'; echo $hash; }"