Search code examples
windowsbatch-fileuser-accounts

Why is the variable disapearing?


I made a names.bat file that will make a folder called profiles then add a batch in the profiles folder to view the profiles and I'm having a problem with the creation of program veiwer.bat the names.bat contains this code:

@echo off
TITLE Profiles
SET /a YEAR=%DATE:~6,4%
if not exist Profiles mkdir Profiles
CD Profiles
ECHO @echo off>"Profile Viewer.bat"
ECHO :profile>>"Profile Viewer.bat"
ECHO title Profile Viewer>>"Profile Viewer.bat"
ECHO SET /P NAME=Search names:>>"Profile Viewer.bat"
ECHO call %NAME%.bat>>"Profile Viewer.bat"
ECHO goto profile>>"Profile Viewer.bat"
GOTO RES
:RES
SET /P NAME=State your name:
ECHO @echo off>%NAME%.txt
ECHO title %NAME%>>%NAME%.txt
ECHO echo Name:%NAME%>>%NAME%.txt
SET /P AGE=State your Age:
ECHO echo Age:%AGE%>>%NAME%.txt
SET /a YOB=%YEAR%-%AGE%
SET /P A=Where you born in %YOB%(Y/N)
IF %A%==Y goto YES
IF %A%==y goto YES
IF %A%==N goto NO
IF %A%==n goto NO

:NO
SET /P YOB=State your Year of birth:
ECHO echo Birth Date:%YOB%>>%NAME%.txt
goto CONTINUE

:YES
ECHO echo Birth Date:%YOB%>>%NAME%.txt
goto CONTINUE

:CONTINUE
ECHO pause>>%NAME%.txt
rename *.txt *.bat
start %NAME%.bat
%SystemRoot%\explorer.exe "C:\Users\%username%\Desktop\Profiles"
echo Here is your profile
pause

so I edit "Profile Viewer.bat" to see if it works it has this

@echo off
:profile
title Profile Viewer
SET /P NAME=Search names:
call .bat
goto profile

Where did the %NAME% variable go? I want it to be in the profile viewer.bat i know its an empty variable i want it to literally say in the code this;

@echo off
:profile
title Profile Viewer
SET /P NAME=Search names:
call %NAME%.bat
goto profile

I know I could make it myself but I want name.bat to do it for me


Solution

  • ECHO call %NAME%.bat>>"Profile Viewer.bat"
    

    When this line is executed, the %NAME% variable is expanded. Since it hasn't been defined yet, it expands to nothing. Thus, we get the erroneous line in Profile Viewer.bat.

    To prevent %NAME% from being expanded, we need to tell the command interpreter that we want an actual % instead of starting a variable. So, we need to escape the % like so:

    ECHO call %%NAME%%.bat>>"Profile Viewer.bat"