2

I'm trying to return value to my batch script. In powershell this script works fine:

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

When i try from batch:

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

I get errors, but this script works fine:

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%

What am I doing wrong?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Antiokh
  • 73
  • 8

2 Answers2

5

In order to avoid need of escaping single quotes use useback parameter.Put everything in double quotes to avoid need of escaping brackets (and mind that -UFormat also accepts single quotes for the format):

for /f "usebackq" %%a in (`"powershell (Get-Date -Uformat '%%w.%%Y-%%m-%%d').Replace('0.', '7.')"`) do set datestamp=%%a
echo %datestamp%
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • `usebackq` is a great idea, but I suggest wrapping only the (implied) `-Command` argument (the string containing the PowerShell commands) in `"..."`: `for /f "usebackq" %%a in (\`powershell -Command "(Get-Date -Uformat '%%w.%%Y-%%m-%%d').Replace('0.', '7.')"\`) do set datestamp=%%a`. If you need to _embed_ `"` chars. inside the command string, use `\""` in _Windows PowerShell_ (`powershell.exe`) or, more simply and robustly, `""` in _PowerShell [Core] 6+_ (`pwsh.exe`). – mklement0 Feb 29 '20 at 13:18
2

I've found my mistake. I need to escape comma-character. Now it looks strange, but works.

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%
Antiokh
  • 73
  • 8
  • 2
    comma is a standard delimiter in batch files as long as ``,``,`,`,`;` and `=` and needs to be escaped in for loops. – npocmaka Apr 10 '17 at 12:58
  • To rephrase @npocmaka's helpful comment: all the characters mentioned function as _argument separators_. – mklement0 Apr 10 '17 at 13:50