defect122

Windows Batch - User input in a batch

Feb 16th, 2012
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Batch Files - User Input
  2.  
  3. The "set" command is also able to pass user input.
  4.  
  5. This is done by set /p.
  6.  
  7. For example:
  8.  
  9. @echo off
  10. echo Type something!
  11. set /p test="Input :"
  12. exit
  13.  
  14. test is the variable. "Input :" is printed on the screen and prompts the user for input.
  15. If you just type this in a batch. The user can type anything he wants.
  16. To narrow this down, you can use the "IF" statement and check if the user typed what he was supposed
  17. to.
  18. The following code does this:
  19.  
  20. @echo off
  21. echo Type s to exit this batch!
  22. set /p test="Input :"
  23. if %test%==s ( echo Good job
  24. ) else ( echo You did not type the correct letter! )
  25. pause > nul
  26. exit
  27.  
  28. What this does is it prompts the user to write something, if this is not the letter s, the if statement check fails and prints
  29. "You did not type the correct letter!".
  30.  
  31. > nul quashes the output of any text by not sending it to the CLI.
  32.  
  33. One way to extent this code is to add an option to it that gives the user three tries to type the wanted letter. This can be achieved by working with
  34. jumpmarks and if statements.
  35.  
  36. @echo off
  37. echo Type q. You have three tries!
  38. set /p input="Type: "
  39. if %input%==q ( goto JUMP ) else ( goto IF1 )
  40. :IF1
  41. echo You have two more tries!
  42. set /p input="Type: "
  43. if %input%==q ( goto JUMP ) else ( goto IF2 )
  44. :IF2
  45. echo You have one more try!
  46. set /P input="Type: "
  47. if %input%==q ( goto JUMP ) else ( goto FAIL )
  48.  
  49. :FAIL
  50. echo You failed!
  51. pause>nul
  52. exit
  53.  
  54. :JUMP
  55. echo Well done!
  56. pause>nul
  57. exit
  58.  
  59. The following batch asks the user over and over again to type the right letter, by just setting a jumpmark at the very beginning of the code.
  60.  
  61. @echo off
  62. :J1
  63. echo Type s to start a program!
  64. set /p var1="Input:"
  65. if %var1%==s ( goto J2 ) else ( goto J1 )
  66. :J2
  67. echo Well done! That was just a test!
  68. pause
  69. exit
  70.  
  71. Note: The input-variable can be empty, you don´t need to specify a string.
  72.  
  73. set /p input=
  74.  
  75. Which displays nothing.
Advertisement
Add Comment
Please, Sign In to add comment