Rob van der Woude's Scripting Pages

User Input

Sometimes we need some user interaction in our batch files.
We may need to know to which directory a file is to be copied, for example.
Or which drive needs to be formatted.

There are many ways to achieve this user interaction.

The most basic form of user interaction, of course, is the PAUSE command, which halts the batch file until the user presses "any key" (apart from Ctrl, Alt, Shift, CapsLock, NumLock or ScrollLock).
Maybe not really sophisticated, but it works and is always available, in all DOS, Windows and OS/2 versions.

How you can manage to retrieve user input depends on the OS version used, and whether you want to allow "third party" tools or use "native code" only.

Windows 2000 and later versions

As of Windows 2000, user input can be obtained quite easily by using SET /P

SET /P variable=[promptString]

This command will display an optional promptString where the user can type in a string and press Enter. The typed string will then be stored in the specified environment variable variable.

Warning: Working with a stored string containing ampersands and doublequotes may cause your batch file to fail or even to execute "unexpected" code (code insertion).
Do not use SET /P in batch files running with elevated privileges!

Windows NT 4 and later versions

In NT we don't need temporary files and we can skip a few lines by using TYPE CON and FOR /F:

  1. @ECHO OFF
  2. :: UserInNT.bat
  3. :: How to use the TYPE CON command to receive user input
  4. :: Written by Rob van der Woude
  5. :: http://www.robvanderwoude.com
  6.  
  7. ECHO.
  8. ECHO Demonstration of receiving user input through the TYPE CON command.
  9. ECHO Type in any string and close by pressing Enter, F6 (or Ctrl+Z), Enter.
  10. ECHO Only the last non-empty line will be remembered, leading spaces are ignored.
  11. ECHO.
  12.  
  13. :: Only one single command line is needed to receive user input
  14. FOR /F "tokens=*" %%A IN ('TYPE CON') DO SET INPUT=%%A
  15. :: Use quotes if you want to display redirection characters as well
  16. ECHO You typed: "%INPUT%"
  17.  

It is still just as un-intuitive as the first COPY CON example, though.

 
Click to download the ZIPped sources
 
Update: Replace TYPE CON by MORE in the above NT batch file and you can save yourself pressing Enter once — you'll need to press F6, Enter only instead of Enter, F6, Enter, though the latter will still work.
[Tip posted by "Frank" on alt.msdos.batch.nt]

Tom Lavedas' New and Improved Data Input Routine! shows a way to use a graphical box to ask for user input in Windows 95

Duke Communications International, Inc.'s tip #0323: How can I get a batch file to prompt me for parameters? shows a way to get a graphical box asking for user input in Windows NT

My own DialogBoxes (executables, written in C#) can be used to display messages and ask for input in Windows XP and later versions.

Walter Zackery posted two interesting solutions to obtain user input in NT, on the alt.msdos.batch.nt news group.

One solution uses the FORMAT command, which will fail since it tries to format a diskette in drive A: at 160KB.
If you have a 5¼" drive as your A: drive don't use this one.

The second solution uses the LABEL command.
It will actually change drive C:'s volume label and then restore it again to its old value.
The volume label in NT is restricted to 32 characters, and so is the input string when using this LABEL trick for user input.
Besides that the batch file limits the string to 2 words (1 space) only.

I adapted the original postings so that the batch files no longer need to use temporary files. You can view the original postings at my Solutions found at alt.msdos.batch page.

Using FORMAT:

  1. @ECHO OFF
  2. :: Obtaining user input in Windows NT
  3. :: with the use of the FORMAT command
  4. :: posted August 20,1999
  5. :: Author: Walter Zackery
  6. :: Adapted by Rob van der Woude
  7. :: (no longer uses temporary file)
  8. :: http://www.robvanderwoude.com
  9.  
  10. SET INPUT=
  11. CLS
  12. ECHO\
  13. ECHO Enter your input string and press ENTER when done.
  14. ECHO\
  15. FOR /F "tokens=5* delims= " %%A IN ('FORMAT /F:160 A: ^| FIND "..."') DO SET INPUT=%%B
  16. SET INPUT
  17.  

Using LABEL:

  1. @ECHO OFF
  2. :: Obtaining user input in Windows NT
  3. :: with the use of the LABEL command
  4. :: posted August 20,1999
  5. :: Author: Walter Zackery
  6. ::
  7. :: Adapted by Rob van der Woude
  8. :: (no longer uses a temporary file;
  9. :: redirection of label command's
  10. :: standard error prevents label command's
  11. :: own prompt to be displayed on screen)
  12.  
  13. CLS
  14. ECHO.
  15. FOR /F "tokens=5* delims= " %%A IN ('VOL C: ^| FIND "drive C"') DO SET OLDLABEL=%%B
  16. ECHO Enter some input string, containing no more than 32 characters:
  17. FOR /F "TOKENS=*" %%? IN ('LABEL C: 2^>NUL') DO SET INPUT=%%?
  18. SET INPUT
  19. LABEL C: %OLDLABEL%
  20.  
 
Click to download the ZIPped sources  
 

Clay Calvert posted another interesting solution to obtain Yes or No input in most DOS versions by using DEL's /P switch (prompt for confirmation).

Another great solution by Eric Phelps uses a temporary HTA file to obscure a password while it is being typed.

MS-DOS

In the MS-DOS 3 days, a simple Yes/No question could be answered by changing to a temporary directory where two temporary batch files were located, Y.BAT and N.BAT.
Guess what happened if a user typed a completely different answer . . .

Since MS-DOS 6 we have CHOICE.COM (CHOICE.EXE in later versions), a much more versatile and reliable way to solve one character answers like Yes/No.

The CHOICE command was discontinued in Windows NT 4, only to be reintroduced again in Windows 7 (and maybe Vista?).
If you work with one of these "challenged" Windows versions, you may want to try my Poor Man's Choice instead, or use DEBUG to create REPLY.COM (16-bit, won't work in a 64-bit OS), as published in Microsoft Knowledge Base article Q77457: Accepting Keyboard Input in Batch Files.

There is another way to receive user input: COPY CON

The command:

COPY CON filename

copies the user input on the command line to the file filename.
To stop entering user input, the user has to type Ctrl+Z (or F6), followed by the Enter key.

Many PC users and batch file authors (including myself), find this approach "less intuitive", to say the least. One would expect that pressing the enter key is enough, and once you find out it isn't, the previous line of input cannot be removed anymore.

The following trick uses ANSI to perform some key translation: the Enter key is translated to the F6 key followed by the Enter key. Thus only one line of input can be entered, and pressing the Enter key sends the input to the temporary file USERINP.TMP.

  1. ECHO Enter some input, and press Enter when ready . . .
  2. ECHO ←[13;0;64;13p
  3. COPY CON USRINPUT.TMP
  4. ECHO ←[13;13p
  5. CLS
  6. ECHO You typed:
  7. TYPE USRINPUT.TMP
Note: The character is the Esc character, or ASCII character 27 (or 1B Hexadecimal).
It is a representation of the Esc key.
This Esc character is not to be confused with escape characters!

How to create the Esc character depends on the editor you use:

• In EDIT, use Ctrl+P followed by Alt+27 (press Alt, keep it pressed, and then type 27 on the numeric key pad).
• In Notepad or Wordpad, copy and paste the Escape character from some reference file you can create using EDIT.
• In Norton Commander or File Commander's editor, use Ctrl+Q followed by Alt+27 on the numeric key pad.
• In E and EPM (OS/2) just type Alt+27 on the numeric key pad.
• In UltraEdit, press Ctrl+I followed by the Esc key.

You may have to change the codepage to 437 in some editors.

The previous example is only a bare minimum. The following example not only asks for user input, but stores it in an environment variable USRINPUT as well:

  1. @ECHO OFF
  2. REM * Ask for USeR INPUT and store it in variable USRINPUT
  3. REM * Assumes ANSI.SYS is loaded
  4. REM * Written by Rob van der Woude
  5.  
  6. SET USRINPUT=
  7.  
  8. REM * Turn on ANSI key translation (translate Enter
  9. REM * key to F6+Enter sequence) and ask for input:
  10. ECHO ←[13;0;64;13pEnter one word only . . .
  11.  
  12. REM * Copy entered text to temporary file:
  13. COPY CON %TEMP%.\~USRINP.TMP
  14.  
  15. REM * Turn off ANSI key translation and clear irrelevant screen output:
  16. ECHO ←[13;13p←[3A←[K←[1B←[K←[1B←[K←[2A
  17.  
  18. REM * Add empty line to temporary file. The empty line
  19. REM * will be used to stop DATE asking for new date.
  20. ECHO.>> %TEMP%.\~USRINP.TMP
  21. ECHO.>> %TEMP%.\~USRINP.TMP
  22.  
  23. REM * Create a temporary batch file that will store the
  24. REM * entered text into the environment variable USRINPUT:
  25. TYPE %TEMP%.\~USRINP.TMP | DATE | FIND "):" > %TEMP%.\~USRINP.BAT
  26.  
  27. REM * Create more temporary batch files. Add
  28. REM * more command line parameters if necessary,
  29. REM * as in: ECHO SET USRINPUT=%%3 %%4 %%5 %%6 %%7 %%8 %%9>CURRENT.BAT
  30. ECHO SET USRINPUT=%%3>CURRENT.BAT
  31.  
  32. REM * VOER.BAT and TYP.BAT are replacements for CURRENT.BAT for Dutch
  33. REM * DOS versions; add your own language versions if necessary:
  34. ECHO SET USRINPUT=%%6>VOER.BAT
  35. ECHO SET USRINPUT=%%4>TYP.BAT
  36.  
  37. REM * This temporary batch file now sets the variable USRINPUT:
  38. CALL %TEMP%.\~USRINP.BAT
  39.  
  40. REM * Display the result:
  41. ECHO You typed: ←[1m%USRINPUT%←[0m
  42. ECHO.
  43. PAUSE
  44.  
  45. REM * Finally, clean up the mess of temporary files:
  46. FOR %%A IN (%TEMP%.\~USRINP.BAT %TEMP%.\~USRINP.TMP VOER.BAT TYP.BAT CURRENT.BAT) DO DEL %%A
  47.  
Click to download the ZIPped sources

The previous batch file should work in every DOS version, assuming ANSI.SYS (or one of its replacements, like ANSI.COM) is loaded.
With a few minor adjustments (replace .BAT with .CMD everywhere) it can be used in OS/2 as well. Use READLINE instead, however, in OS/2's DOS sessions.

The following batch file checks if ANSI.SYS is loaded. If so, it will tell the user to press the Enter key only. If not, it will tell the user to press F6 first, followed by the Enter key.
However, to check if ANSI.SYS is loaded, this batch file needs MS-DOS 6 or later.

  1. @ECHO OFF
  2. REM * Asks for USeR INPut and store it in variable USRINPUT
  3. REM * Uses ANSI if available, but works without ANSI too
  4. REM * Assumes MS-DOS 6 or later
  5. REM * Written by Rob van der Woude
  6.  
  7. SET USRINPUT=
  8.  
  9. REM * Check if ANSI sequences can be used (needs at
  10. REM * least MS-DOS 6 to get an errorlevel from FIND):
  11. SET ANSI=1
  12. MEM /C | FIND "ANSI" > NUL
  13. IF ERRORLEVEL 1 SET ANSI=0
  14.  
  15. REM * Turn on ANSI key translation (translate Enter
  16. REM * key to F6 + Enter sequence) if possible:
  17. IF "%ANSI%"=="1" ECHO ←[13;0;64;13p
  18.  
  19. REM * Ask for input:
  20. IF "%ANSI%"=="0" ECHO Enter one word only, and press F6 followed by Enter . . .
  21. IF "%ANSI%"=="1" ECHO Enter one word only, and press Enter . . .
  22.  
  23. REM * Copy entered text to temporary file:
  24. COPY CON %TEMP%.\~USRINP.TMP
  25.  
  26. REM * Turn off ANSI key translation and clear irrelevant screen output:
  27. IF "%ANSI%"=="0" CLS
  28. IF "%ANSI%"=="1" ECHO ←[13;13p←[3A←[K←[1B←[K←[1B←[K←[2A
  29.  
  30. REM * Add empty line to temporary file. The empty line
  31. REM * will be used to stop DATE asking for new date.
  32. ECHO.>> %TEMP%.\~USRINP.TMP
  33. ECHO.>> %TEMP%.\~USRINP.TMP
  34.  
  35. REM * Create a temporary batch file that will store the
  36. REM * entered text into the environment variable USRINPUT:
  37. TYPE %TEMP%.\~USRINP.TMP | DATE | FIND "):" > %TEMP%.\~USRINP.BAT
  38.  
  39. REM * Create more temporary batch files. Add
  40. REM * more command line parameters if necessary,
  41. REM * as in: ECHO SET USRINPUT=%%3 %%4 %%5 %%6 %%7 %%8 %%9>CURRENT.BAT
  42. ECHO SET USRINPUT=%%3>CURRENT.BAT
  43.  
  44. REM * VOER.BAT and TYP.BAT are replacements for CURRENT.BAT for Dutch
  45. REM * DOS versions; add your own language versions if necessary:
  46. ECHO SET USRINPUT=%%6>VOER.BAT
  47. ECHO SET USRINPUT=%%4>TYP.BAT
  48.  
  49. REM * This temporary batch file now sets the variable USRINPUT:
  50. CALL %TEMP%.\~USRINP.BAT
  51.  
  52. REM * Display the result:
  53. IF "%ANSI%"=="0" ECHO You typed: %USRINPUT%
  54. IF "%ANSI%"=="1" ECHO You typed: ←[1m%USRINPUT%←[0m
  55. ECHO.
  56. PAUSE
  57.  
  58. REM * Finally, clean up the mess of temporary files:
  59. FOR %%A IN (%TEMP%.\~USRINP.BAT %TEMP%.\~USRINP.TMP VOER.BAT TYP.BAT CURRENT.BAT) DO DEL %%A
  60. SET ANSI=
  61.  
 
Click to download the ZIPped sources
 

Batch Tools

There are many batch utilities on the web that help ask for user input.
I will list some of them here:

KiXtart

A non-batch solution for Windows 95/98/NT/2000 users is the GetS( ) function in KiXtart:

  1. @ECHO OFF
  2. :: UsrInKix.bat,  Version 1.00 for Win32
  3. :: Batch file using Kix to retreive user input
  4. :: Written by Rob van der Woude
  5. :: http://www.robvanderwoude.com
  6.  
  7. :: Create a temporary Kix script that will
  8. :: in turn create a temporary batch file:
  9. > %TEMP%.\UserIn.kix ECHO REDIRECTOUTPUT( "NUL" )
  10. >>%TEMP%.\UserIn.kix ECHO GETS $UserIn
  11. >>%TEMP%.\UserIn.kix ECHO IF OPEN( 1, "@SCRIPTDIR\UserIn.bat", 5 ) = 0
  12. >>%TEMP%.\UserIn.kix ECHO     WRITELINE( 1, "SET UserIn=" + $UserIn )
  13. >>%TEMP%.\UserIn.kix ECHO ELSE
  14. >>%TEMP%.\UserIn.kix ECHO     ? "Error opening temporary file, errorcode = " + @ERROR
  15. >>%TEMP%.\UserIn.kix ECHO ENDIF
  16. :: Prompt for user input:
  17. ECHO Type anything you like and press Enter when finished:
  18. :: Retreive user input using the Kix script, and
  19. :: then store the result in a temporary batch file:
  20. KIX32.EXE %TEMP%.\UserIn.kix
  21. :: Call the temporary batch file to store
  22. :: the result in an environment variable:
  23. CALL %TEMP%.\UserIn.bat
  24. :: Clean up the temporary files:
  25. IF EXIST %TEMP%.\UserIn.* DEL %TEMP%.\UserIn.*
  26. :: Finaly, display the result:
  27. ECHO You typed: %UserIn%
  28.  
 
Click to download the ZIPped sources
 

OS/2

OS/2 users may want to take a look at UserInPM, a utility written in VX-Rexx, displaying a small PM window asking for user input.
It creates a temporary batch file to set an environment variable to the typed input.
An example batch file, with the resulting PM window:

  1. SET USRINPUT=
  2. USRINPUT.EXE Type whatever you like:
  3. CALL USRINPUT.CMD
  4. ECHO User input: %USRINPUT%
USRINPUT dialogue window

You will need the VX-Rexx runtime library VROBJ.DLL to run UserInPM.

PowerShell

For a login dialog, you can also use the following PowerShell code:

  1. # Dialog asking for credentials
  2. $cred = Get-Credential $username
  3. # Return username and password, delimited by a semicolon
  4. Write-Host $cred.GetNetworkCredential( ).UserName -NoNewline
  5. Write-Host ";" -NoNewline
  6. Write-Host $cred.GetNetworkCredential( ).Password

Save it as login.ps1, and use it to return the user name and password to a batch file:

  1. FOR /F "tokens=1* delims=;" %%A IN ('PowerShell ./login.ps1 %UserName%') DO (
  2. 	SET Usr=%%A
  3. 	SET Pwd=%%B
  4. )

My LoginDialog.ps1 is based on the code above, with some error handling added:

  1. param(
  2. 	[string]$UserName = $null,
  3. 	[switch]$TabDelimited,
  4. 	[switch]$h,
  5. 	[parameter( ValueFromRemainingArguments = $true )]
  6. 	[object]$invalidArgs
  7. )
  8.  
  9. if ( $h -or $invalidArgs ) {
  10. 	Write-Host
  11. 	Write-Host "LoginDialog.ps1,  Version 1.01"
  12. 	Write-Host "Present a login dialog, and return the user name and password"
  13. 	Write-Host
  14. 	Write-Host "Usage:  " -NoNewline
  15. 	Write-Host "./LoginDialog.ps1  [ username ]  [ -TabDelimited ]" -ForegroundColor White
  16. 	Write-Host
  17. 	Write-Host "Where:  " -NoNewline
  18. 	Write-Host "username           " -ForegroundColor White -NoNewline
  19. 	Write-Host "is the optional user name presented in the dialog"
  20. 	Write-Host "        -TabDelimited      " -ForegroundColor White -NoNewline
  21. 	Write-Host "tab delimited output (default delimiter: semicolon)"
  22. 	Write-Host
  23. 	Write-Host "Written by Rob van der Woude"
  24. 	Write-Host "http://www.robvanderwoude.com"
  25. 	Exit 1
  26. } else {
  27. 	Try
  28. 	{
  29. 		# Dialog asking for credentials
  30. 		$cred = Get-Credential $UserName
  31.  
  32. 		# Return username and password, delimited by a semicolon (default) or tab (switch -TabDelimited)
  33. 		Write-Host $cred.GetNetworkCredential( ).UserName -NoNewline
  34. 		if ( $TabDelimited ) {
  35. 			Write-Host "`t" -NoNewline
  36. 		} else {
  37. 			Write-Host ";" -NoNewline
  38. 		}
  39. 		Write-Host $cred.GetNetworkCredential( ).Password
  40. 	}
  41. 	Catch
  42. 	{
  43. 		Write-Host "-- Canceled --"
  44. 		Exit 1
  45. 	}
  46. }

With LoginDialog.ps1, catching a login error in the batch file is easy:

  1. FOR /F "tokens=1* delims=;" %%A IN ('PowerShell ./LoginDialog.ps1 %UserName%') DO (
  2. 	SET Usr=%%A
  3. 	SET Pwd=%%B
  4. )
  5. IF "%Usr%"=="-- Canceled --" (
  6. 	SET Usr=
  7. 	SET Pwd=
  8. 	ECHO The login was canceled
  9. )

VBScript

More advanced dialog boxes, output and input, including (masked) password prompts, can be created using VBScript and Internet Explorer, but I would not recommend creating them on the fly.

Sample change password dialog created using VBScript and Internet Explorer

See the VBScript Scripting Techniques section for some of these advanced user message windows.


page last uploaded: 2018-02-13, 23:49