0

This is my code:

set /p name=user save name
if %name%==[""]
cd c:\users\student\desktop\login system\usersXD
echo set "name=%name%"> %name%.bat

My code is not working. and i will like to load them up to view

  • 1
    What is _"is not working"_? What does it do or not do? What type input do you provide in the `set /p` entry? What do you expect it to do? You need to understand that you are also matching things thart makes no sence. `if %name%==[""]` will only match if your input is exactly `[""]` but then even if it did match, you do nothing after that on the same line. You also need to wrap paths in Double quotes, especially if they have whitespace. `cd "c:\users\student\desktop\login system\usersXD"` – Gerhard Dec 06 '19 at 05:41

2 Answers2

0

I suggest following code for this task:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
goto PromptName

:ErrorInvalid
echo(
echo Error: The character !InvalidChar! is not allowed in name.
echo(
endlocal

:PromptName
set "Name="
set /P "Name=User save name: "
rem Has the user not input anything?
if not defined Name goto PromptName
rem Remove all double quotes from input string.
set "Name=%Name:"=%"
rem Has the user input just double quotes?
if not defined Name goto PromptName

rem Check if the input string contains any character not allowed in a file name.
setlocal EnableDelayedExpansion
for %%I in ("<" ">" ":" "/" "\" "|") do if not "!Name:%%~I=!" == "!Name!" set "InvalidChar=%%~I" & goto ErrorInvalid
if not "!Name:?=!" == "!Name!" set "InvalidChar=?" & goto ErrorInvalid
if not "!Name:**=!" == "!Name!" set "InvalidChar=*" & goto ErrorInvalid
endlocal

cd /D "%UserProfile%\Desktop\login system\usersXD"
echo set "Name=%Name%">"%Name%.bat"
endlocal

The file name of the batch file to create must be enclosed in double quotes because it could contain a space or one of these characters &()[]{}^=;!'+,`~ which require enclosing the file name in double quotes.

This batch file should not be stored in directory %UserProfile%\Desktop\login system\usersXD on having file extension .bat as it could be overwritten during execution if the user enters a name the name of the batch file. It would be safe to have this batch file in that directory with file extension .cmd.

The batch file is still not 100% fail-safe despite the checks already added, but the user input string itself cannot result anymore in an exit of batch file execution because of a syntax error.

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • cd /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?

See also:

Mofi
  • 46,139
  • 17
  • 80
  • 143
0

This should work to save a variable in a bat file If I remember

  (
  Echo set test=% 
  Echo set test=%test%
  Echo set test=%test%
  )>Test.bat
Gloxidia
  • 1
  • 5