0

I am currently facing a weird issue while executing batch script. The date output works after 4th attempt of executing the script in the same command prompt instance.

Note : I am opening new instance of command prompt and then executing the batch script to fetch the date values but however the values does not appear and I need to execute the same script 4 times to get actual date values in the same instance of command prompt.

Below is the sample script.

@echo off

FOR %%x IN (1 2 3) DO (

    echo submit > test.txt
    (
        echo testdata
    ) >> test.txt

    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 Iteration :::: %%x
    echo datestamp: "%datestamp%" , timestamp: "%timestamp%", fullstamp: "%fullstamp%"

)

Screen shot of the output:

enter image description here

Anonymous
  • 325
  • 1
  • 3
  • 8

1 Answers1

2

You are not using setlocal / endlocal. So the variables you create remain in memory and these variables with their values will be shown in the next run. You are using () command blocks and are not using delayed expansion. This means variables will always be used with the value they have at the start of the command block. There are several ways to deal with these problems.

First isolate your batch from the environment. This can be done by using setlocal at the start and endlocal at the end of your batchfile. This is the preferred way. This can als be done by initialising all used variables at the start of the batchfile. This will remove left-over values from previous runs.

The commandblock problem. There are two ways to deal with this. First method: use enabled delayed expansion and the corresponding !var! syntax. Second method: use 'call set' and 'call echo' with the corresponding syntax of doubling the % in the varnames. This will force using the up-to-date values from the variables inside a command block.

OJBakker
  • 602
  • 1
  • 5
  • 6