1

In a Windows 7 batch file, I can call powershell v2 to create a string and then assign that string to a batch file variable to later use within another command, like this:

for /f "delims=" %%a in ('powershell -noninteractive -NoProfile -Command "Get-Date -format 'yyyy-MM-dd HH_mm_ss'"') do set "datetime=%%a"
rem process file1.txt here
ren file1.txt "newname %datetime%.txt"

If I try to do the same thing (within a batch file), in a simpler way, it doesn't work:

Editor's note: Turns out it does work - the inner " instances are correctly escaped as \".

powershell -noninteractive -NoProfile -Command "$datetime_string = Get-Date -format 'yyyy-MM-dd HH_mm_ss'; (gc file1.txt) -join [char]10 | Out-File -Encoding Ascii \"newname $datetime_string.txt\""

Can you help?

4
  • 1
    @TessellatingHeckler Hmmm... stackoverflow.com/a/44637674/4182398 states otherwise, or am I misunderstanding it? Commented Jun 20, 2017 at 0:09
  • 1
    @RockPaperLizard: Re \": you're not misunderstanding: when PowerShell is invoked from the outside world (such as from a batch file), " chars. must indeed be escaped as \" - which is surprising and little-known, given that within PowerShell you must embed " chars. inside "..." as `" Commented Jun 20, 2017 at 1:29
  • 1
    @RockPaperLizard wow, it is. I thought ^ was the command prompt escape. Beg 'pardon. Commented Jun 20, 2017 at 2:26
  • @TessellatingHeckler: ^ only works when it is used unquoted. Inside a double-quoted string (from cmd's perspective), the only thing that cmd itself recognizes is "", which, however, is only recognized by MS-compiled programs and, with limitations, by batch files. For the whole sordid tale, see this answer of mine. Commented Jun 20, 2017 at 14:32

1 Answer 1

2

If the inner double quotes are a problem, you can simply avoid them:

powershell -NonI -NoP -Com  "$DT=Get-Date -format 'yyyy-MM-dd HH_mm_ss';(gc file1.txt) -join [char]10|Out-File ('newname '+$DT+'.txt') -Enc Ascii"

For brevity parameter and variable names are shortened as much as possible.

Sign up to request clarification or add additional context in comments.

1 Comment

++ for a viable alternative, but it's worth noting that the OP's command actually does work, due to correctly escaping embedded " instances as \". That said, your approach is ultimately preferable, because it avoids the risk of cmd unexpectedly interpreting a part of the command line itself, due to not recognizing \" as an escaped double quote and actually considering it the end of a double-quoted string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.