Search code examples
batch-filebatch-rename

Use Double Delayed Expansion to SET a variable in a batch file


So I'm trying to use double delayed expansion to rename files in a directory. The issue I'm having is using double delayed expansion with the SET command. This method works as expected with the ECHO command. Why does this not work with SET?

Below is an extract of my code, re-written to work in a standalone script. This script has the same output as my main code and uses similar values.

@echo off
TITLE Bug In File Renaming
SETLOCAL enableextensions enabledelayedexpansion

:: The directory 'C:\Users\admin\Desktop\testFolder\Images'
:: contains 7 .png files named
:: Game-Prize-BANOFFEE_PIE.png
:: Game-Prize-BLUEBERRY_PIE.png
:: Game-Prize-BRANDY_BUTTER.png
:: Game-Prize-BUTTER_CREAM_CUP_CAKE.png
:: Game-Prize-CANDIED_NUTS.png
:: Game-Prize-CARAMELS.png
:: Game-Prize-CARROT_CAKE.png


SET renameFileDirectory=C:\Users\admin\Desktop\testFolder\Images
SET renameFilePrefix=Game-Prize-
SET renameFileType=.png
SET newValuesList[0]=VALUE1
SET newValuesList[1]=VALUE2
SET newValuesList[2]=VALUE3
SET newValuesList[3]=VALUE4
SET newValuesList[4]=VALUE5
SET newValuesList[5]=VALUE6
SET newValuesList[6]=VALUE7
echo.  newValuesList & echo [%newValuesList[0]%, %newValuesList[1]%, %newValuesList[2]%, %newValuesList[3]%, %newValuesList[4]%, %newValuesList[5]%, %newValuesList[6]%]
SET /a i=0
FOR %%G IN (%renameFileDirectory%\%renameFilePrefix%*%renameFileType%) DO (
    call echo newValue = %%newValuesList[!i!]%%
    call SET newValue=%%newValuesList[!i!]%%
    call echo newNewValue = %newValue%
    SET /a i+=1
)

PAUSE
 ----OUTPUT----
   newValuesList
 [VALUE1, VALUE2, VALUE3, VALUE4, VALUE5, VALUE6, VALUE7]
 newValue = VALUE1
 newNewValue =
 newValue = VALUE2
 newNewValue =
 newValue = VALUE3
 newNewValue =
 newValue = VALUE4
 newNewValue =
 newValue = VALUE5
 newNewValue =
 newValue = VALUE6
 newNewValue =
 newValue = VALUE7
 newNewValue =
 Press any key to continue . . .

The main line I think has the issue is call SET newValue=%%newValuesList[!i!]%%

Is this line possible? As I understand this is double delayed expansion and should set the variable 'newValue' to the same value as 'newValuesList[0]' (when i=0) which should be VALUE1


Solution

  • @jeb had the answer, so thought I'd postit as an official answer to close the question.

    Change call echo newNewValue = %newValue% to echo newNewValue = !newValue!