嵌套的for循环内的if语句中分配的未设置变量值

时间:2019-03-08 10:46:14

标签: batch-file for-loop if-statement

我正在尝试制作一个批处理文件以从文件中读取参数,并将其传递给ant进行部署。

我制作了以下批处理文件:

setlocal enabledelayedexpansion
echo on

IF EXIST "D:\testfile1.txt" (
    echo Do one thing

    set string=
    set /p string=< D:\testfile1.txt
    echo value taken from file is %string

    for /f "tokens=2,4,6 delims==:" %%G IN ("%string%") DO (

        echo %%G %%H %%I
        set env=%%G
        set dom=%%H
        set com=%%I
        echo ENV !env!
        echo DOM !dom!
        echo COM !com!


        cd D:\kpn_eai\EAI_FIXED\branches\kpn_eai_fixed\fixed\build\scripts

        %ANT_HOME%\bin\xanteai deploy %%G %%H %%I

    )
) ELSE (
    echo Do another thing
)

endlocal

testfile1.txt中,我有以下格式的参数:

Environment=Env_Name1:Domain=Domain_Name1:Component=Component_name1

参数是不同的部署。当我运行上面的代码时,它给出下面的输出

D:\>echo off
Do one thing Ant home is C:\tibco\ant\apache-ant-1.9.13
value taken from file is Environment=Env_name1:Domain=Domain_Name1:Component=Component_name1
Env_name1 Domain_Name1 Component_name1
ENV Env_name1
DOM Domain_Name1
COM Component_name1

此后开始部署。

我面临的问题是当我为不同的参数(在testfile1.txt中)运行代码时 ENVDOM和{{1 }}保持不变,无论从COM读取的任何参数如何。

有人可以帮助我更正此代码,让我知道如何将从文件中读取的值分配给变量,然后将其传递给testfile1.txt进行部署吗?

注意:-该批处理文件将被放置在调度程序中,当发现文件部署过程被触发时,它将每5分钟检查一次ant。因此,我包括了if条件来检查文件的可用性。

2 个答案:

答案 0 :(得分:1)

实际上,您不需要set放置或echo随身携带所有东西,所以为什么不做这样的事情呢?

@Echo Off
If Exist "testfile1.txt" (Set /P "string="<"testfile1.txt"
    SetLocal EnableDelayedExpansion
    Echo value taken from file is !string!
    For /F "Tokens=2,4,6 Delims==:" %%A In ("!string!") Do (
        CD /D "D:\kpn_eai\EAI_FIXED\branches\kpn_eai_fixed\fixed\build\scripts"
        "%ANT_HOME%\bin\xanteai" deploy %%A %%B %%C)
    EndLocal) Else Echo Do another thing

答案 1 :(得分:0)

您可以先使用简单的for和
在冒号处拆分读取行。 从内容中获取变量名env,dom,com

在此前面带有下划线,以便于输出。

:: Q:\Test\2019\03\08\SO_55061545_.cmd
@echo off
setlocal enabledelayedexpansion
set "FileIn=D:\testfile1.txt"

IF not EXIST "%FileIn%" (
    echo Do another thing
    Goto :somewhere
)

echo Do one thing
set "string="
set /p "string="<"%FileIn%"
echo value taken from file is %string%

for %%A in ("%string::=" "%") do for /f "tokens=1* delims==" %%B IN ("%%~A") DO (
    echo %%A %%B %%C
    set var=%%B
    set "_!var:~0,3!=%%C"
)
set _

:: cd D:\kpn_eai\EAI_FIXED\branches\kpn_eai_fixed\fixed\build\scripts
:: %ANT_HOME%\bin\xanteai deploy %_env% %_dom% %_com%

endlocal

:somewhere

>  SO_55061545_.cmd
Do one thing
value taken from file is Environment=Env_Name1:Domain=Domain_Name1:Component=Component_name1
"Environment=Env_Name1" Environment Env_Name1
"Domain=Domain_Name1" Domain Domain_Name1
"Component=Component_name1" Component Component_name1
_Com=Component_name1
_Dom=Domain_Name1
_Env=Env_Name1