I want to execute a function in PowerShell from Windows CMD. Basically the requirement is to calculate the hash of a string, since Windows batch/cmd does not provide the functionality to generate a hash of a string, I've to use PowerShell.
I don't want to run a PowerShell script or put the function in a ps script as by doing so I have to bypass the Windows PowerShell security policy.
Below is the code which I am running in Hash.cmd. The code, when executed in PowerShell, runs perfectly fine.
@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; }"
But this is resulting in error on CMD as below:
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-----
"sha1"/"x2"/"Hello world"to single quotes.