如果条件不在批处理文件的for循环中执行 [英] If condition is not being executed in for loop of batch file

查看:75
本文介绍了如果条件不在批处理文件的for循环中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在批处理文件中调用msbuild命令.

We are calling msbuild command in batch files.

我们已经通过批处理文件的for循环传递了参数.

We have passed the parameters via for loop of batch file.

FOR %%C in (
    CommonInfrastructure
    CommonUtilities
    ) do ( 
        msbuild /t:%BuildCmdType% %BuildFile%  /p:Group=%%C %msbuildLogger% /p:Configuration=Release
        if %ERRORLEVEL% NEQ 0 (
        msbuild /t:SendFailureMail /p:ErrorLogFileName=%ErrorLog% %BuildFile%
        set ErrorBuild=1
        )
    )

当我分析日志文件时,我看到If块中的代码没有被执行.

When i analyzing the log file, I am seeing that code in If block is not being executed.

由于未发送通知邮件.

如何使它在有条件的情况下执行?

How to make it to execute if condition ?

推荐答案

jeb正确诊断了您的问题,并提供了很好的解决方案.您还有其他选择.

jeb correctly diagnosed your problem and provided a good solution. You have other options.

IF ERRORLEVEL 1 ...(不包含百分比)检查ERRORLEVEL是否大于或等于1.只要msbuild从不返回负的ERRORLEVEL,这应该可以工作.

IF ERRORLEVEL 1 ... (without percents) checks if the ERRORLEVEL is greater than or equal to 1. That should work as long as msbuild never returns a negative ERRORLEVEL.

FOR %%C in (
    CommonInfrastructure
    CommonUtilities
) do ( 
    msbuild /t:%BuildCmdType% %BuildFile%  /p:Group=%%C %msbuildLogger% /p:Configuration=Release
    if ERRORLEVEL 1 (
        msbuild /t:SendFailureMail /p:ErrorLogFileName=%ErrorLog% %BuildFile%
        set ErrorBuild=1
    )
)


您可以通过使用变量和IF(NOT)DEFINED来测试任何非零值而无需使用扩展


You can test for any non-zero value without using expansion by use of a variable and IF (NOT) DEFINED

set "success="
FOR %%C in (
    CommonInfrastructure
    CommonUtilities
) do ( 
    msbuild /t:%BuildCmdType% %BuildFile%  /p:Group=%%C %msbuildLogger% /p:Configuration=Release
    if errorlevel 0 if not errorlevel 1 set success=1
    if not defined success (
        msbuild /t:SendFailureMail /p:ErrorLogFileName=%ErrorLog% %BuildFile%
        set ErrorBuild=1
    )
)


我的首选解决方案是仅在先前命令失败时才使用||运算符有条件地执行命令. (注意-还有&&运算符可在成功执行时有条件地执行)


My preferred solution is to use the || operator to conditionally execute commands only if the prior command failed. (Note - there is also the && operator to conditionally execute upon success)

FOR %%C in (
    CommonInfrastructure
    CommonUtilities
) do ( 
    msbuild /t:%BuildCmdType% %BuildFile%  /p:Group=%%C %msbuildLogger% /p:Configuration=Release || (
        msbuild /t:SendFailureMail /p:ErrorLogFileName=%ErrorLog% %BuildFile%
        set ErrorBuild=1
    )
)

这篇关于如果条件不在批处理文件的for循环中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆