Search code examples
windowsbatch-filecmddelayedvariableexpansion

Evaluating a DelayedExpansion variable as a drive letter when checking for file existence


I've got this block of code that's supposed to check for USB drives, then if they have a file that tags them as one of my utility drives, it runs a robocopy sync on them to make sure they're current.

The problem is it's not evaluating the path for the file correctly. If I echo "!curDrive!\file.txt" It prints \file.txt"

The relevant (cleaned up/anonymized) bits of script are:

@echo off
Setlocal EnableDelayedExpansion
for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=2 and access=0" get name /format:value') DO (
    SET "curDrive=%%d"
    echo Looping variable set to %%d
    echo Current drive set to !curDrive!
    if exist "!curDrive!\file.txt" (
        ...
    )
)

The echos I've put in for debugging, and I get the expected output on all iterations, e.g.,

Looping variable set to L:
Current drive set to L:

Solution

  • Try this:

    @echo off
    Setlocal EnableDelayedExpansion
    for /f %%d in ('wmic logicaldisk where "drivetype=2 and access=0" get name^|find ":"') DO (
        SET "curDrive=%%d"
        if exist "!curDrive!\file.txt" (
           Echo found it. 
        ) ELSE (
           Echo File not found. 
        )
    )
    

    You're returning extra carriage returns that need to be filtered out.