I have the below code snippet which outputs a variable in to a text file.
%drone%
will be a simple text string, and the %counter%
is a number which is in a loop to count the iterations.
The echo %drone% !counter!
echos the correct values to the screen but in the echo Done: %drone% Files deleted: !tempcounter! >> clearTempFilesonDrones.txt
code the !tempcounter!
variable is blank when outputted to the file.
I've tried to set it to a temp variable and use %tempvariable%
, but that didn't work. I also tried like "!counter!"
incase it would think that that's a string instead of just a number, but didn't work either.
echo %drone% %counter%
endlocal
echo Done: %drone% Files deleted: !counter! >> clearTempFilesonDrones.txt
Any ideas?
I can't copy the entire code onto a pastebin or the like as blocked in current client, so just uploaded an extract.
It looks like behavior of setlocal
without or with 1 or 2 of the optional 4 parameters and endlocal
is not really known by you.
See the answers on
which describe in detail with examples what setlocal
and endlocal
really do.
The current values of the environment variables drone
and counter
must be passed from current environment variables table deleted by endlocal
to the restored environment variables table active before setlocal
and active again after endlocal
.
This can be done as follows:
echo %drone% %counter%
endlocal & set "drone=%drone%" & set "counter=%counter%"
echo Done: %drone% Files deleted: %counter% >>clearTempFilesonDrones.txt
The entire command line with the command endlocal
and the two set
commands is first preprocessed by Windows command processor with the values of current environment variable resulting in replacing the variable references by their current values. So the line is after preprocessing:
endlocal & set "drone=value of drone variable" & set "counter=counter value"
Now first endlocal
is executed which discards the current environment variables table and restores previous environment variables table. Then then two set
commands are executed which assigns the two strings to the two variables in now active environment variables table.
For an explanation of operator &
see the answer on Single line with multiple commands using Windows batch file.
Further I suggest to open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
endlocal /?
set /?
setlocal /?
The built-in help is not so detailed as the referenced answers, but should be nevertheless read.