Escape characters when executing powershell command in batch script

前提是你 提交于 2019-12-05 21:09:12

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))

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