如果使用批处理文件不存在则设置环境变量

问题描述 投票:0回答:1

我试图设置一个环境变量,以防它不存在,如果它存在,脚本将退出。我正在尝试使用以下代码。

@echo off
echo %machine% > c:\machineoutput.txt
findstr /I /c:"C:\Oracle\Ora12c\perl\bin" c:\machineoutput.txt
if %errorlevel% == 0 (
    goto SETPATH
) else (
    EOF
)
:SETPATH
setx /m machine "%oracle_home%\perl\bin;%path%"
:EOF
exit

但有些人如何不按预期工作。我能够设置变量,但即使变量存在,它再次设置它然后退出。

请帮我找出我做错了什么。

batch-file windows-server-2012
1个回答
0
投票

我不知道你为什么检查C:\Oracle\Ora12c\perl\bin是否存在于非标准环境变量machine中以确定是否应将%oracle_home%\perl\bin添加到系统环境变量PATH中。我建议检查系统PATH是否存在此目录路径。

EOF没有有效的命令。因此,Windows命令处理器输出错误消息并继续使用下一个命令行作为setx的行。这就是您的批处理代码不起作用的原因。 ELSE分支中的命令应该是goto :EOF

更好的方法是遵循代码检查系统PATH中是否存在%oracle_home%\perl\bin或其扩展的等价物,如果系统路径中不存在,则附加而不是将其预先添加到系统PATH。

@echo off
if not exist "%oracle_home%\perl\bin\*" goto :EOF
setlocal EnableExtensions DisableDelayedExpansion

for /F "skip=2 tokens=1,2*" %%N in ('%SystemRoot%\System32\reg.exe query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v "Path" 2^>nul') do (
    if /I "%%N" == "Path" (
        set "SystemPath=%%P"
        if defined SystemPath goto CheckPath
    )
)
echo Error: System environment variable PATH not found with a non-empty value.
echo/
endlocal
pause
goto :EOF

:CheckPath
setlocal EnableDelayedExpansion
set "Separator="
set "PathToAdd=%%oracle_home%%\perl\bin"
set "OraclePerlPath=%oracle_home%\perl\bin"
if not "!SystemPath:~-1!" == ";" set "Separator=;"
if "!SystemPath:%PathToAdd%=!" == "!SystemPath!" (
    if "!SystemPath:%OraclePerlPath%=!" == "!SystemPath!" (
        set "PathToSet=!SystemPath!%Separator%!PathToAdd!"
        set "UseSetx=1"
        if not "!PathToSet:~1024,1!" == "" set "UseSetx="
        if not exist %SystemRoot%\System32\setx.exe set "UseSetx="
        if defined UseSetx (
            %SystemRoot%\System32\setx.exe Path "!PathToSet!" /M >nul
        ) else (
            set "ValueType=REG_EXPAND_SZ"
            if "!PathToSet:%%=!" == "!PathToSet!" set "ValueType=REG_SZ"
            %SystemRoot%\System32\reg.exe ADD "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /f /v Path /t !ValueType! /d "!PathToSet!" >nul
        )
    )
)
endlocal
endlocal

有关此批处理代码的详细信息,请阅读Why are other folder paths also added to system PATH with SetX and not only the specified folder path?上的答案,该答案用作此批处理代码的模板。它还解释了为什么有问题的批处理代码肯定不是很好。

注1:命令setx默认在Windows XP上不可用。

注1:命令setx截断长度超过1024个字符到1024个字符的值。

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

  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • reg /?reg add /?reg query /?
  • set /?
  • setlocal /?
  • setx /?
© www.soinside.com 2019 - 2024. All rights reserved.