批处理脚本如何检查变量是否存在然后用另一个替换变量

时间:2015-12-07 06:28:57

标签: variables batch-file

我已经尝试过每一个如何做到这一点,但我不知道如何做。 如何检查是否定义了变量,以及是否使用不同的变量替换该文件中的每个变量。感谢

好的,这是代码

@echo off
set/p "directoryname= Name of directory (to run on startup type "startup").    : "
if %directoryname%==startup goto startup

:namedirectory
if not exist "%directoryname%" (
mkdir "%directoryname%"
if "!errorlevel!" EQU "0" (
echo Folder created successfully
) else (
echo Error while creating folder
)
) else (
echo Folder already exists
)

goto skip_startup

:startup
:: here i would like to check if the variable %directoryname% is defined,
:: and  it is, replace the variable named %directoryname% with
:: (Not changing the variables name) with the directory,
:: "C:\Documents and Settings\All Users\Start Menu\Programs\Startup". that
:: way when ever i can recall my variables in my file i can change my folder
:: to the startup directory.

:skip_startup 
cd %directoryname%

::        ^
::        |_ replaced variable

1 个答案:

答案 0 :(得分:1)

以下是批量代码,其中包含了所请求的以及更多增强功能:

@echo off

rem Define as default directory name "startup". The user has to hit just
rem ENTER or RETURN with this default value and variable DirectoryName
rem keeps the default value "startup". Then ask user for directory name
rem and remove all double quotes from the entered directory name.

:EnterDirectory
set "DirectoryName=startup"
echo Please enter name of directory.
echo.
echo Hit just RETURN or ENTER to run on startup directory.
echo.
set /p "DirectoryName=Name of directory: "
set "DirectoryName=%DirectoryName:"=%"

rem Check if something other than just 1 or more double quotes was entered.
rem Prompt user once more after clearing screen if this is really the case.
if "%DirectoryName%" == "" cls & goto EnterDirectory

if "%DirectoryName%" == "startup" goto Startup

rem Check if entered directory name does not contain only spaces.

if "%DirectoryName: =%" == "" cls & goto EnterDirectory

echo.
if not exist "%DirectoryName%" (
    mkdir "%DirectoryName%"
    if errorlevel 1 (
        echo Error on creating folder %DirectoryName%
    ) else (
        echo Folder %DirectoryName% created successfully.
    )
) else (
    echo Folder %DirectoryName% already exists.
)
goto SetDirectory

rem The variable DirectoryName has the default value "startup". Replace
rem this value by directory path of "Startup" folder in all users start
rem menu of Windows.

:Startup
set "DirectoryName=%ALLUSERSPROFILE%\Start Menu\Programs\Startup"

rem Set current directory to "Startup" directory or entered directory.

:SetDirectory
cd /D "%DirectoryName%"

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • cd /?
  • cls /?
  • echo /?
  • goto /?
  • if /?
  • mkdir /?
  • rem /?
  • set /?

并阅读: