从cmd调用powershell命令时出错

Ant*_*okh 2 powershell escaping batch-file quoting

我正在尝试将值返回到我的批处理脚本。在 powershell 中,此脚本运行良好:

PS> (Get-Date -Date "9.04.2017" -Uformat "%w.%Y-%m-%d").Replace("0.", "7.")
7.2017-04-09
Run Code Online (Sandbox Code Playgroud)

当我尝试批量时:

for /f %%a in ('powershell ^(Get-Date -Uformat "%%w.%%Y-%%m-%%d"^).Replace^(^'0.^', ^'7.^'^)') do set datestamp=%%a
echo %datestamp%
Run Code Online (Sandbox Code Playgroud)

我收到错误,但这个脚本工作正常:

for /f %%a in ('powershell ^(get-date^).DayOfWeek') do set weekday=%%a
for /f %%a in ('powershell Get-Date -Uformat "%%u.%weekday%.%%Y-%%m-%%d"') do set datestamp=%%a
echo %datestamp%
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

npo*_*aka 5

为了避免需要转义单引号,请使用useback参数。将所有内容放在双引号中以避免需要转义括号(请注意 -UFormat 也接受格式的单引号):

for /f "usebackq" %%a in (`"powershell (Get-Date -Uformat '%%w.%%Y-%%m-%%d').Replace('0.', '7.')"`) do set datestamp=%%a
echo %datestamp%
Run Code Online (Sandbox Code Playgroud)