When variables are set in a normal batch script, they persist in the environment until they are deleted or the environment is closed. Your problem stems from the fact that you gave %studentName%
a value without preparing the environment first. You have two options:
Option 1: Clear the variable before using it
@echo off
:: Clears the value of %studentName%. The quotes are to prevent extra spaces from sneaking onto the end
set "studentName="
:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name:
::If the user does not input anything go to end option
if "%studentName%"=="" goto end
:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%
:: Pauses screen while user reads secret number
pause
:: Clear screen for user.
cls
echo Hope you remeber that number, %studentName%!
:end
echo Usage: %0 studentName
pause
exit /b
Pros:
- If you need other variables to persist, you can run this over and over and they will stay until the command prompt is closed.
Cons:
- If you have a lot of variables that need to not persist, you need to clear each one manually.
Option 2: Using setlocal to create a new environment
@echo off
setlocal
:: Sets variable studentName to what the user inputs.
set /p studentName=Enter student name:
::If the user does not input anything go to end option
if "%studentName%"=="" goto end
:: Displays filename, student's entered name, and the random number
echo Usage: %0 %studentName%
echo Hello %studentName%, your secret number is %RANDOM%
:: Pauses screen while user reads secret number
pause
:: Clear screen for user.
cls
echo Hope you remeber that number, %studentName%!
:end
echo Usage: %0 studentName
pause
exit /b
Pros:
- If you have a lot of variables to clear, this will save a ton of typing.
If When you need to use delayed expansion, you'll need to use this method anyway
Cons:
- Variable values won't persist across multiple runs unless you store them somewhere