如何将变量保存到批处理文件?

时间:2019-12-06 05:17:24

标签: batch-file

这是我的代码:

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

我的代码不起作用。我想加载它们以查看

2 个答案:

答案 0 :(得分:0)

对于此任务,我建议使用以下代码:

@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

要创建的批处理文件的文件名必须用双引号引起来,因为它可能包含空格或这些字符&()[]{}^=;!'+,`~中的一个,需要将文件名用双引号引起来。

此批处理文件不应以文件扩展名%UserProfile%\Desktop\login system\usersXD存储在目录.bat中,因为如果用户输入名称作为批处理文件的名称,则该批处理文件可能在执行期间被覆盖。将该批处理文件放在文件扩展名为.cmd的目录中是安全的。

尽管已经添加了检查,但批处理文件仍不是100%故障安全的,但是由于语法错误,用户输入字符串本身再也不能导致退出批处理文件。

要了解所使用的命令及其工作方式,请打开documentation窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。

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

另请参阅:

答案 1 :(得分:0)

这应该可以将变量保存在bat文件中 如果我还记得

  (
  Echo set test=% 
  Echo set test=%test%
  Echo set test=%test%
  )>Test.bat