0

Based on answers and comments from this question, I cannot understand how to add a double-pipe || statement with two commands using the && on a for loop. Consider the following example taken from here:

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

If I try

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" || echo Error while getting datetime. >> %someoutputfile% && GOTO endthis

I get a Unexpected && error. I tried adding parenthesis around the each command after the || but they too give Unexpected ) similar errors.

Can someone explain what I am doing wrong? Should I put the || commands before the do set "dt=%%a" or something?

2 Answers2

1

You may also use this approach:

(for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a") || rem

if errorlevel 1 echo Error while getting datetime. >> %someoutputfile% & GOTO endthis

This method is fully described below Exit Code management at this answer.

Aacini
  • 59,374
  • 12
  • 63
  • 94
0

Here's a working example:

@ echo off

for /f "tokens=2 delims==" %%a in ('WMIC OS Get LocalDateTime /value') do (
    set dt=%%a && (
        echo Local Data Time: "%dt%"
    ) || (
        echo Error while getting datetime.
        goto ERROR
    )
)

echo Exiting...
goto END

:ERROR
echo Terminating...

:END
Azeem
  • 7,094
  • 4
  • 19
  • 32
  • Isn't this applying the checks for the error (i.e. the two commands after the `||`) only to the `set dt=%%a` command and not to the whole `for` loop? –  Jul 07 '17 at 12:53
  • @Karim: Yes. The syntax is for the command. The `for` loop doesn't have a separate syntax like this. – Azeem Jul 07 '17 at 15:03