raddacle
raddacle

Reputation: 1

Batch: How to scroll through files to read to a variable?

I'm trying to have it scroll through a directory and present a new variable when the user replies "N". I have it all figured out except how to go to the next variable.

cd "C:\Test"
for /r %%F in (*) do SET Show=%%~NF
echo %Show%
echo.
SET /P Continue=Continue?(Y/N)
if /I "%Continue%" EQU "y" goto :Run
if /I "%Continue%" EQU "n" goto :Start

Upvotes: 0

Views: 498

Answers (2)

Compo
Compo

Reputation: 38708

Is this what you need:

For /R "C:\Test" %%A In (*) Do (Choice /M "%%~nA"
    If Not ErrorLevel 2 (Set "Show=%%~nA" & GoTo Run))
Exit /B
:Run
Echo Running against %Show%
Pause

Alternatively, should you wish to return to the loop after running against the file name, then use Call instead of GoTo:

For /R "C:\Test" %%A In (*) Do (Choice /M "%%~nA"
    If Not ErrorLevel 2 Call :Run "%%~nA")
Exit /B
:Run
Set "Show=%~1"
Echo Running against %Show%
Pause

Upvotes: 0

John Kens
John Kens

Reputation: 1679

If you're looking to scroll the directory and prompt the user the file name and have them choose to choose it or continue, then bellow should help you.

Firstly, we can use dir /b /a:d to display only directories (folders) in the the current directory. By using a code block ( & ) we can put batch script inside the for loop. For your sake, we can use the CHOICE command to prompt to continue the loop or to save current folder to string and do something with it.

ScrollTreeWithPrompt.bat:

@echo off
setlocal EnableDelayedExpansion

Rem | Configuration
Set "MainDir=C:\Test"

Rem | Get Each Project Folder
for /f "tokens=*" %%A in ('dir "!MainDir!\" /b /a:d') do (

    Cls
    Echo Current Folder: %%A
    echo(
    CHOICE /M "Continue?"

    Rem | Check for "N" - If so Set String & goto
    IF "!ERRORLEVEL!"=="2" (
        Set "Choice=%%A"
        GOTO Run
    )
)

Rem | No Further Results
Cls
Echo Warning: No further folders found.

pause>NUL
goto :EOF

:Run
Cls
echo Currently selected: !MainDir!\!Choice!

pause>NUL
goto :EOF

I have left a few Rem comments in the script to help you along. For any more help on the commands, type the following into a command prompt:

  • choice /?
  • set /?
  • for /?
  • goto /?

Upvotes: 2

Related Questions