我正在参加Windows命令行课程,我收到的批处理文件中有一条我不明白的错误消息。我应该创建一个批处理文件,它接受参数并打印它们是否是环境变量。这就是我到目前为止所做的:
:: Disable echoing of batch file commands to console.
@echo off
rem ********Begin Header******************
:: Author: Megan
:: Date: 04/08/2018
:: File: checkVars.bat
:: Descr:
:: This script determines if a given
:: set of arguments are defined
:: environmental variables.
rem ********End Header********************
:: Check to make sure at least one command
:: line argument has been given. If not,
:: display a usage message and exit the
:: batch file.
if "%1" == "" (
echo Usage: %0 varname1 ...
echo Determines if variable name is defined
exit /b 1
)
:: determine if arguments %1 and greater
:: are environmental variables
:again
if not "%1" == "" (
if defined %1 (
echo %1 is a defined environment variable.
echo.
) else (
echo %1 is NOT a defined environment variable.
echo.
)
shift /1
goto again
)
当我使用命令 checkVars windir mydir prompt myvar 运行批处理文件时,我得到以下输出:
windir is a defined environmental variable.
mydir is NOT a defined environmental variable.
prompt is a defined environmental variable.
myvar is NOT a defined environmental variable.
The syntax of the command is incorrect.
看起来我的代码正在运行一次额外的时间。任何人都可以帮我指出我的错误方向吗?
答案 0 :(得分:0)
看了你的代码后,我注意到你需要用引号括起一些部分。导致语法错误的主要原因是if defined %1
,其中%1
需要变为"%1"
。希望这能解决你的问题。
更正代码:
:: Disable echoing of batch file commands to console.
@echo off
rem ********Begin Header******************
:: Author: Megan
:: Date: 04/08/2018
:: File: checkVars.bat
:: Descr:
:: This script determines if a given
:: set of arguments are defined
:: environmental variables.
rem ********End Header********************
:: Check to make sure at least one command
:: line argument has been given. If not,
:: display a usage message and exit the
:: batch file.
if "%1" == "" (
echo Usage: %0 varname1 ...
echo Determines if variable name is defined
)
:: determine if arguments %1 and greater
:: are environmental variables
:again
if not "%1" == "" (
if defined "%1" (
echo %1 is a defined environment variable.
echo.
) else (
echo %1 is NOT a defined environment variable.
echo.
)
shift /1
goto again
)