2

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

1
  • I'm sure it's to do with delayed expansion... like !DBFileName! ... i'll keep at it! Commented Jul 28, 2011 at 0:16

1 Answer 1

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 
2
  • Thank you for the help. I just worked it out, will post solution Commented Jul 28, 2011 at 0:25
  • If that doesn't work - using a CALL SET in :SetVar might do the trick. Edit: Missed your last comment. :) Commented Jul 28, 2011 at 0:28

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.