gpt4 book ai didi

Windows 批处理命令 : How to dereference FOR loop variable to check if that variable is SET in Environment Variable

转载 作者:可可西里 更新时间:2023-11-01 11:28:30 27 4
gpt4 key购买 nike

我正在编写一个批处理命令脚本,其中检查环境变量。我需要通过传递所有必需的变量来编写一个 FOR 循环,然后验证它是否已定义,如果未定义,则提示该键的值并永久设置该变量。

问题是我无法取消引用循环变量并在环境变量中检查它。

示例代码如下:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%G IN (JBOSS_HOME, JAVA_HOME, ANT_HOME, PERFORCE_PATH, P4CLIENT) DO (
ECHO.
ECHO. Loop Item : %%G
:: Call a function by sending each value to check if it is set in ENVIRONMENT Variables, if not then add it persistently.
CALL:validateAndUpdate %%G
)
GOTO:EOF

:validateAndUpdate
:: Now I have to check if passed value is available in ENVIRONMENT variable or not
:: echo %~1 will print value like JBOSS_HOME
:: Below IF condition always substitues to IF ("JBOSS_HOME" == []) and it always returns true
:: but could not find syntax to use it to DE-reference and check if that key is set.
:: Ex: IF %JBOSS_HOME% == []

IF ("%~1" == []) (
ECHO.
ECHO. %~1 is empty
SET /p value="Enter value for '%~1' : "

:: Set that key value pair persistently using SETX
SETX %~1 "%value%"
) ELSE (
ECHO.
ECHO. %~1 is available as ENVIRONMENT variable
)

GOTO:EOF

ENDLOCAL

最佳答案

要检查变量是否已定义,请在 if 语句中使用 defined 关键字。 help if 了解更多信息。

如果我可以提出另一个建议,最好为用户显示一个文件夹选择器,而不是让他手动输入路径名。为此,将此概念证明保存为 .bat 扩展名并进行试用。看看它是否像您想要的那样工作:

@if (@a==@b) @end   /* JScript multiline comment

:: based on https://stackoverflow.com/a/15906994/1683264
:: batch portion

@echo off
setlocal enabledelayedexpansion

for %%G in (windir, temp, foo, bar) do (
if not defined %%G (
call :chooser %%G "Locate directory for %%G."
) else echo %%G is already defined as !%%G!
)

goto :EOF

:chooser <var_to_set> <dialog_title>
for /f "delims=" %%I in ('cscript /nologo /e:jscript "%~f0" "%~2"') do (

rem :: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
rem :: Remove the "echo" from this next line when you are satisfied
rem :: that it will do what you intend.
rem :: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
echo setx %~1 "%%~I"

)
goto :EOF

:: JScript portion */

var shl = new ActiveXObject("Shell.Application");
var folder = shl.BrowseForFolder(0, WSH.Arguments(0), 0, 0x00);
WSH.Echo(folder ? folder.self.path : '');

在您对模拟按照您的预期进行感到满意后,从 :chooser 子例程中删除 echo

参见 this page有关从 .bat 脚本启动文件或文件夹选择器的更多方法,请参阅 this GitHub Gist有关 JScript/批处理混合的更多详细信息和更多示例。

关于Windows 批处理命令 : How to dereference FOR loop variable to check if that variable is SET in Environment Variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27475403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com