Question

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:
Was it helpful?

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.

OTHER TIPS

Here is another method you can use in a defined system, looking for a unique file on a drive and then running robocopy. Add the rest of the drive letters.

@echo off
for %%a in (c d e f g h i j) do if exist "%%a:\unique-file.txt" echo found the file.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top