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?

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    @TessellatingHeckler Hmmm... https://stackoverflow.com/a/44637674/4182398 states otherwise, or am I misunderstanding it? – RockPaperLz- Mask it or Casket Jun 20 '17 at 00: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 `\`"` – mklement0 Jun 20 '17 at 01:29
  • 1
    @RockPaperLizard wow, it is. I thought `^` was the command prompt escape. Beg 'pardon. – TessellatingHeckler Jun 20 '17 at 02: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](http://stackoverflow.com/a/31413730/45375) of mine. – mklement0 Jun 20 '17 at 14:32

1 Answers1

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.

  • ++ 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. – mklement0 Jun 20 '17 at 14:38