if 和 else 块都在批处理脚本中执行

Both if and else block are executed in Batch script

我是批处理脚本的新手。 我正在尝试编写一个脚本来解析给定的命令,并检查该命令中是否存在名为“folder”的参数,如果不存在,则添加具有默认值的参数。

我写了下面的脚本。如果缺少参数,此脚本将正确执行。 但是如果存在参数,则执行 if 和 else 块。

请帮忙。提前致谢。

@echo off

set ARGS=-action generate -folder "Source"
set t=%ARGS%

echo %t%|find "-folder" >nul
if errorlevel 1 (
    goto setDefaultFolder
) else (
    echo Folder is specified in command
)

:setDefaultFolder
echo Folder is NOT specified in command. User's current directory will be used as Folder.
set folderArgName=-folder
set folderArgValue="%cd%"
set folderArg=%folderArgName% %folderArgValue%
echo folderArgName : %folderArgName%
echo folderArgValue : %folderArgValue%
echo folderArg: %folderArg%
set ARGS=%ARGS% %folderArg%
echo ARGS : %ARGS%

代码输出:

Folder is specified in command
Folder is NOT specified in command. User's current directory will be used as Folder.
folderArgName : -folder
folderArgValue : "C:\work"
folderArg: -folder "C:\work"
ARGS : -action generate -folder "Source" -folder "C:\work"

你必须在 else 中有一个 goto,在 setDeafultFolder 之后,否则它只会执行它之后的 setDefaultFolder

@echo off

set ARGS=-action generate -folder "Source"
set t=%ARGS%

echo %t%|find "-folder" >nul
if errorlevel 1 (
    goto setDefaultFolder
) else (
    echo Folder is specified in command
    goto endOfBatch
)

:setDefaultFolder
echo Folder is NOT specified in command. User's current directory will be used as Folder.
set folderArgName=-folder
set folderArgValue="%cd%"
set folderArg=%folderArgName% %folderArgValue%
echo folderArgName : %folderArgName%
echo folderArgValue : %folderArgValue%
echo folderArg: %folderArg%
set ARGS=%ARGS% %folderArg%
echo ARGS : %ARGS%

:endOfBatch