Search code examples
powershellbatch-filecmdquoting

How to use line continuation inside quoted string of FOR /F


I would like to be able to specify multiple lines for the command of a FOR /F loop. The first three (3) commands work as expected. However, the fourth (4th) command will never let me make a newline while inside the quoted command. I have tried the cmd.exe line continuation character caret, the PowerShell line continuation character backtick, and combined caret+backtick. It seems to simply skip over the fourth (4th) FOR /F loop without error or message.

Yes, I see that the fourth (4th) FOR /F loop is not in danger of overrunning the right side of the display. I am thinking of times when I have much longer commands. Is creating a .ps1 file the only answer? Can line continuation be made to work?

C:>type gd.bat
@ECHO OFF
FOR /F "usebackq tokens=*" %%d IN (`powershell -NoProfile -Command "get-date -format s"`) DO (SET "DT_STAMP=%%d")
ECHO DT_STAMP 1 is %DT_STAMP%

FOR /F %%d IN ('powershell -NoProfile -Command "Get-Date -Format s"') DO (SET "DT_STAMP=%%d")
ECHO DT_STAMP 2 is %DT_STAMP%

FOR /F %%d IN ('powershell -NoProfile -Command ^
    "Get-Date -Format s"') DO (SET "DT_STAMP=%%d")
ECHO DT_STAMP 3 is %DT_STAMP%

FOR /F %%d IN ('powershell -NoProfile -Command ^
    "Get-Date ^`
        -Format s"') DO (SET "DT_STAMP=%%d")
ECHO DT_STAMP 4 is %DT_STAMP%

19:53:02.34  C:\src\t
C:>gd.bat
DT_STAMP 1 is 2018-01-07T19:53:10
DT_STAMP 2 is 2018-01-07T19:53:10
DT_STAMP 3 is 2018-01-07T19:53:10
20:01:39.37  C:\src\t
C:>echo %ERRORLEVEL%
0

Solution

  • You are attempting to do cmd.exe line continuation. The ^ has no special meaning if quoting is ON. You can escape the " as ^" so that the ^ line continuation works. You must also escape the second quote, else the closing ) will not be recognized.

    FOR /F %%d IN ('powershell -NoProfile -Command ^
        ^"Get-Date ^
            -Format s^"') DO (SET "DT_STAMP=%%d")
    

    Note that the line breaks are purely cosmetic - Powershell still receives the entire command as a single line (without any line breaks).