2017-04-10 171 views
2

我试图将值返回给我的批处理脚本。 在PowerShell中这个脚本工作正常:从cmd调用powershell命令时出错

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

,当我从一批尝试:

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

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

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% 

我在做什么错?

+0

*“我有一个错误”*所以,它说什么? –

+0

另外:我想不出为什么你会尝试从批处理中做到这一点的任何理由? – bluuf

+0

我有一个很大的批处理脚本,我只需要一个powershell调用。也许以后我会把剧本改写成PowerShell。 – Antiokh

回答

4

为了避免需要逃逸单引号使用useback parameter.Put一切都在双引号,以避免需要转义括号的(和记-UFormat也接受的格式单引号):

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

谢谢,这也有帮助 – Antiokh

2

我发现我的错误。我需要逃避逗号。 现在看起来很奇怪,但工程。

for /f %%a in ('powershell ^(Get-Date -Date "9.04.2017" -Uformat "%%w.%%Y-%%m-%%d"^).Replace^(^'0.^'^,^'7.^'^)') do set datestamp=%%a 
echo %datestamp% 
+2

逗号是批处理文件中的标准分隔符,只要'','',',';'和'='需要在for循环中转义。 – npocmaka

+0

要改写@ npocmaka的有用评论:所有提到的字符都用作_argument分隔符_。 – mklement0