views:

193

answers:

1

A user will give me an absolute path - say "C:\src" (passed into %1 in the batch file). Then, I need to find the directory entitled "SQLScripts" that is in some subfolder of "C:\src".

How can I find the absolute path to the "SQLScripts" directory? Also, I'm not worrying about multiple instances of the SQLScripts directory existing.

From my Googling, the solution may involve a for loop and some batch modifier such as %~$PATH:1. This link may be beneficial - Special Batch Characters.

All solutions need to work on Windows XP and above.
Note that I'm constrained to using a batch file, and can't use other "easier" methods such as a simple Python code snippet to solve my problem.

Thanks!

+1  A: 

This code saves the path to SQLScripts into %SQLSCRIPTSPATH% variable, and it works on WinXP:

DIR SQLScripts /B /P /S>tmp.txt
for /f "delims=" %%a in (tmp.txt) do set SQLSCRIPTSPATH=%%a
del tmp.txt

EDIT:

Better solution (without using a temporary file) suggested by Joe:

for /f "tokens=*" %%i in ('DIR SqlScripts /B /P /S') do SET SQLSCRIPTSPATH=%%i
SLA80
+1, this will do the trick. The following variant will avoid the creation of a temporary file tmp.txt, and will handle paths that contain spaces. Like the original, it sets SQLSCRIPTSPATH to the last matching path if there is more than one: for /f "tokens=*" %%i in ('DIR SqlScripts /B /P /S') do SET SQLSCRIPTSPATH=%%i
Joe
+1, No temporary file, superb! :)
SLA80
Whenever you see `for /f` with a `dir` command you can ask yourself whether it's really necessary. `for` can iterate over directories or files just fine: `for /d /r %x in (.) do if /i %~nx EQU SqlScripts set SQLSCRIPTSPATH=%~dpnx`
Joey
Johannes, your code returns "The following usage of the path operator in batch-parameter substitution is invalid: %~dpnx". Something wrong, but syntax looks OK to me, and I can't understand what exactly wrong.
SLA80
Johannes, interesting idea. It seems that it's not possible to specify directory for the DIR command to start its search from so using a for loop would probably be a better solution. Replacing (.) with (<user input path>) in this case.
Alex
It IS possible to specify starting directory for DIR comand, just do "cd <user-input-path>" before DIR command. BTW, Alex, is Johannes's code working? I'm asking, because it isn't working on my pc.
SLA80
Good solution. However, if the dir command returns more than one subdirectory called "SQlScripts" (per the original question), once the for loop has completed the variable SQLSCRIPTSPATH will be set to the last subdirectory path returned by the DIR command.
Alex