Dos Batch File Help: Storing %%c variable from FOR loop [Resolved]

batchscripting

It's been a while since i've had to write a batch file, and i'm having trouble with the following:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%a in ('dir f:\*mssql* /ad/b') do (
    for /f %%b in ('dir f:\%%a\data /ad/s/b') do (
        for /f %%c in ('dir %%b\*.mdf /b') do (
            Set DBFileName=%%c
            echo Filename: %DBFileName%
        )
    )
)


ENDLOCAL
GOTO:EOF

I would like to store the variable %%c from the FOR loop into the variable DBFileName, so that I can then pass this variable to other functions.

This batch file isn't complete as yet, but i've hit this roadblock already and i'm STUCK!

Expected output:

Filename: tempdb.mdf
Filename: testdb.mdf
Filename: master.mdf
Filename: model.mdf
Filename: msdb.mdf
Filename: fubar.mdf

Actual output:

Filename:
Filename:
Filename:
Filename:
Filename:
Filename:

Any ideas?
thanks

My answer (not enough rep to answer own question)

It was delayed expansion of variables, bringing back bad memories.

Needed to use ! instead of %

Example script:

:FindSQL
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%a in ('dir f:\*mssql* /ad/b') do (
    for /f %%b in ('dir f:\%%a\data /ad/s/b') do (
        for /f %%c in ('dir %%b\*.mdf /b') do (
            Set DBFileName=%%c
            Echo Filename: !DBFileName!
            Set DBPath=%%b\%%c
        )
    )
)

echo At this point the DBPath variable still works..
echo See?  %DBPath%

ENDLOCAL
GOTO:EOF

By using ! instead of % the script waits to evaluate the variable until it reaches that point

Best Answer

What you might have to do for the FOR statement is CALL a subroutine at pass it %%c as an argument.

For Example:

for /f %%c in ('dir %%b\*.mdf /b') do (call :SetVar"%%c")
...
:SetVar
  Set DBFileName=%1
  echo Filename: %DBFileName%
  goto :eof