问题
I want to execute powershell command and put it in batch variable
The command:
for /f "delims=" %%i in ('powershell ^(Get-ChildItem ""\dir\"" -Name | sort-object {\[regex\]::Replace^($_,^'\d+^',{$args\[0\].Value.PadLeft^(20^)}^)} | select -last 1^) ') do set output=%%i
It can't be executed due special character. In addition, I can't pause the window so it closes before I can see what is the problem.
I think the problem is with the pipe "|", because the following command does work(the part before the pipe)
for /f "delims=" %%i in ('powershell ^(Get-ChildItem ""\dir\"" -Name^) ') do set output=%%i
I tried to add ^
, ^^^
and ""
before pipe, doesn't work. Can you spot the problem?
回答1:
Powershell can accept Base64-encoded commands, which is a handy way to overcome special characters in cmd scripts. Like so,
$command = 'gci -param | stuff | ? { something }'
$bytes = [Text.Encoding]::Unicode.GetBytes($command)
$encoded = [Convert]::ToBase64String($bytes)
$encoded # Get output
ZwBjAGkAIAAtA...
Now that you've got a base64 string, pass it in batch file
set encoded=ZwBjAGkAIAAtA...
for /f "delims=" %%i in ('powershell -encodedCommand %encoded' ...)
To reverse the Base64 encoding, use
[Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encoded))
回答2:
This seems to work with putting the PowerShell script inside "
quotes, without all that escaping everything:
for /f "delims=" %%i in ('powershell.exe "Get-ChildItem c:\temp -Name | Sort-Object -Property { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }| select-object -first 1"') do set output=%%i
来源:https://stackoverflow.com/questions/47172151/escape-characters-when-executing-powershell-command-in-batch-script