Search code examples
batch-filefor-loopscriptingdirectoryuser-input

Prompting user to select directory in batch file


Issue:

I am attempting to have users select which folder to choose from within a specified directory and then add that folder to the address in order to execute a program within that directory.

For example, !acct! is the variable that I am using to ask the end user which account they want to access. This account is the starting or root folder for all other folders. The folder structure remains that same across all accounts EXCEPT for the second token of the folder. i.e) 123456789\*\program\setup\

The * is the folder where multiple folders exist that I would like the end user to choose from.

Once chosen, I would like the script to add that directory so that the program could be executed.

I thought by setting the variable acctDir=C:\Users\jdoe\Desktop\!acct!\ would allow me to add the acct number for the root directory, then run a FOR loop that would allow me to use a wild card in the set for /d %%i in ( !acctdir!*media1\setup ) do ( start !app! )

Any help would be greatly appreciated!

@echo off
setlocal enabledelayedexpansion

:beginning
echo.
echo.
echo ===========================================================
echo Starting on !date! !time! on !Computername!
echo ===========================================================
echo.

goto :main


:main
setlocal

    set /P acct=Please type the 9 digit account number you would like to restore: 
    set acctDir=C:\Users\jdoe\Desktop\!acct!\
    set app=setup.exe /cd
    set log=c:\logs.txt


    echo. Starting on !date! !time! on !Computername! >> !log!
    echo.
    echo The account number you selected is: !acct!
    echo.

    goto :user

:user

    set /p answer=Is this correct (Y/N)? 
    echo.

    if /i !answer!==y goto :yes (
    ) else ( 
        echo.
        echo Ok. Let's try again^^!
        echo.
        Pause
        cls
        goto :beginning
        )
    )

:yes

    for /d %%i in ( !acctdir!*media1\setup ) do (
        start !app!
    )

endlocal
goto :eof

Solution

  • You could try something like the following:

    set c=0
    For /f %%a in ('dir !acctDir! /B /A D') do (
        set /a c+=1
        echo !c!    %%a
        set dir!c!=%%a
    )
    
    echo. 
    set /p uin="Select a directory [1-!c!]: "
    set udir=!dir%uin%!
    
    echo Selected - %udir%
    

    This loops through a directory listing of !acctDir! and prompts the user to select a directory based on the number assigned to it.

    !acctDir!\%udir% will then be the location of the directory.