在批处理脚本中执行powershell命令时转义字符

问题描述:

我想执行powershell命令并将其放入批处理变量

I want to execute powershell command and put it in batch variable

命令:

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?

这似乎可以将PowerShell脚本放在"引号中,而又不会将所有内容转义:

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