-3

In cmd I want to assign the file path of a file say 'test.txt' to a variable name filePath, complete file location is not know, it is know only up to certain folder so I am using dir /b /a /s "test.txt". I am using below syntax :

set filePath=C:\Users\kadamr\AppData\Local\Test>dir /b /a /s "test.txt"

When I echo the value of filePath I get the syntax instead of filePath.

i.e : C:\Users\kadamr\AppData\Local\Test>dir /b /a /s "test.txt"

What I am missing ?

rushikesh
  • 51
  • 1
  • 5
  • 2
    in batch you can't do it this way. You need a [for /f](https://ss64.com/nt/for_cmd.html) loop to capture the output of a command. Did you really try to include the prompt `C:\Users\kadamr\AppData\Local\Test>`? What gave you that idea? – Stephan Jul 04 '20 at 12:12
  • I am new at command line. dir /b /a /s "test.txt" gave the path for file in command line. I wanted to store this output so that I can use it when needed. So tried the thing. – rushikesh Jul 04 '20 at 12:22
  • 1
    Visit the link, I gave you. It explains how to store it. – Stephan Jul 04 '20 at 12:41
  • What about most simple `for /F "delims=" %%I in ('dir "%LocalAppData%\test.txt" /A-D /B /S 2^>nul') do set "filePath=%%~dpI"`? Please note that the file path is assigned with backslash at end to the environment variable `filePath` on at least one file with name `test.txt` found in local application data directory or any of its subdirectories. Run in a command prompt window `cmd /?`, `dir /?` and `for /?` and read carefully the output help for each command from top to bottom. Note: __FOR__ runs the command line between `'` with `%ComSpec% /c` and the command line appended in background. – Mofi Jul 04 '20 at 20:07

1 Answers1

0

If this is always under the users's home directory, use the USERPROFILE variable as the base directory from which to search. Why did you use /a when no attribute is specified? Also, keep in mind that more than one test.txt file may exist somewhere under the base directory.

@ECHO OFF
SETLOCAL
SET "EXITCODE=1"
SET "BASEDIR=%USERPROFILE%\AppData\Local\Test"
FOR /F "delims=" %%A IN ('DIR /S /B "%BASEDIR%\test.txt" 2^>NUL') DO (
    ECHO COMMAND: CALL doit.exe "%%~A"
    IF ERRORLEVEL 1 (SET "EXITCODE=%ERRORLEVEL%" & GOTO TheEnd)
    SET "EXITCODE=0"
)
:TheEnd
EXIT /B %EXITCODE%
lit
  • 14,456
  • 10
  • 65
  • 119