Escape characters when executing powershell command in batch script

≡放荡痞女 提交于 2020-01-02 07:13:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!