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?

4
  • "I have an error" So, what does it say? Commented Apr 10, 2017 at 12:48
  • also : I can't think of any reason why you would try to do this from batch? Commented Apr 10, 2017 at 12:50
  • I have a big batch script, where I need only one powershell call. Maybe later I''rewrite the script to powershell. Commented Apr 10, 2017 at 12:53
  • Closely related: stackoverflow.com/q/60442926/45375 Commented Feb 29, 2020 at 13:20

2 Answers 2

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%
Sign up to request clarification or add additional context in comments.

1 Comment

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

2 Comments

comma is a standard delimiter in batch files as long as <space>,<tab>,,,; and = and needs to be escaped in for loops.
To rephrase @npocmaka's helpful comment: all the characters mentioned function as argument separators.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.