[英]Executing a command in PowerShell by setting an environment variable in cmd
我想從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-----
您遇到了報價問題,因為您在雙引號中使用了雙引號,這會破壞報價。
由於代碼中雙引號的字符串不需要擴展(請參見about_quoting_rules ),因此您只需將雙引號"sha1"
/ "x2"
/ "Hello world"
更改為單引號即可,例如'sha1'
編輯:對我的工作代碼:
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; }"
問題是我在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; }"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.