Search code examples
windowsbatch-filecmd

How to take input from user and change directory


How do I take input from a user and then i.e. change a directory based upon that input.

Example, lets say I ask, please type in directory of A when pressing enter, the directory should change to it and echo out the working directory to the user.

@ECHO OFF 
:: This batch file takes input from the user, delete, copy and install 
new files. 
ECHO Please enter the location of your Zibo folder:
set mydir=%CD%
PAUSE
ECHO your working directory is:
ECHO %mydir%
PAUSE

Solution

  • You can use Set /P to request user input. To find out how, enter set /? at the Command Prompt, and read the output. To change directory, you'd use CD|ChDir, its usage information is also available at the Command Prompt when entering cd /?.

    Here's an example:

    @Echo Off 
    :GetInput
    Set "ZiboDir="
    Rem Request input from the user. 
    Set /P "ZiboDir=Please enter the location of your Zibo directory: "
    Rem If input is not a directory ask again
    For %%G In ("%ZiboDir%") Do If "%%~aG" Lss "d" If "%%~aG" GEq "-" (
        GoTo GetInput) Else GoTo GetInput
    Rem Valid directory detected so continuing
    Echo Your Zibo directory is %ZiboDir%
    Pause
    Rem Make the Zibo directory the current directory
    CD /D "%ZiboDir%"
    Echo Your current directory is %CD%
    Pause