Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

share|improve this question
    
I'm sure it's to do with delayed expansion... like !DBFileName! ... i'll keep at it! –  David W Jul 28 '11 at 0:16

1 Answer 1

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
share|improve this answer
    
Thank you for the help. I just worked it out, will post solution –  David W Jul 28 '11 at 0:25
    
If that doesn't work - using a CALL SET in :SetVar might do the trick. Edit: Missed your last comment. :) –  Doug Luxem Jul 28 '11 at 0:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.