windowsbatch-filedelayedvariableexpansion

Batch loop to create folders from a list containing environment variables


I have a file containing a list of directory paths. I want to create directories at those locations. The paths have system environment variables, set with System Properties ->Environment Variables. Like so:

$COMPLETE_DIR/type1
$COMPLETE_DIR/type1
$COMPLETE_DIR/type1
$INCOMPLETE_DIR/type2
$INCOMPLETE_DIR/type3
$INCOMPLETE_DIR/type4

I made a little loop that is supposed to create the directories as shown above:

@echo off
setlocal enabledelayedexpansion

set "input_file=FolderList.txt"

for /F "usebackq delims=" %%a in ("%input_file%") do (
    set "directory_name=%%~a"
    echo Creating directory: !directory_name!
    if exist "!directory_name!" (
        echo Directory already exists: !directory_name!
    ) else (
        mkdir "!directory_name!" || (
            echo Failed to create directory: !directory_name!
        )
    )
)

echo All directories created or checked successfully.
pause

But this doesn't expand the environment variables. I tried turning off the delayed expansion, but then the for loop breaks, and only one directory is created. How do I partially delay expansion?


Solution

  • Your file have not Batch file "environment variables"... Before continue, lets assume that the name of the variable is just COMPLETE_DIR and NOT $COMPLETE_DIR (that is the way to access the variable value in other language).

    If you change your file to this:

    !COMPLETE_DIR!/type1
    !COMPLETE_DIR!/type2
    !COMPLETE_DIR!/type3
    !INCOMPLETE_DIR!/type2
    !INCOMPLETE_DIR!/type3
    !INCOMPLETE_DIR!/type4
    

    ... then you can use your variables with your exact same code.

    This line:

        set "directory_name=%%~a"
    

    ... imply to execute this (after replacing the %%~a by the first line read):

        set "directory_name=!COMPLETE_DIR!/type1"
    

    Of course, after that the COMPLETE_DIR environment variable is expanded via Delayed Expansion, as usual!