【问题标题】:Batch script: IF compaison is not working as expected批处理脚本:如果比较未按预期工作
【发布时间】:2013-02-25 16:52:26
【问题描述】:
FOR /F "tokens=*" %%A IN ('gpresult /r ^| FIND "string"') DO SET Result=%%A  
if '%Result%'=='this is where the word string shows up'  
echo Success > %homepath%\Desktop\Success.txt  

即使字符串匹配,也不会真正将文件写入桌面。

【问题讨论】:

    标签: windows scripting batch-file


    【解决方案1】:

    你需要

    setlocal enabledelayedexpansion
    

    在批处理文件的顶部,然后是

    '%Result%'=='this is where the word string shows up'
    

    你需要

    '!Result!'=='this is where the word string shows up'
    

    - 注意!代替 %。否则,第一次解析批处理文件时会扩展 %Result%,此时 Result 变量不包含任何内容。这些变化意味着它会延迟解析它,直到它在 for 循环中,此时它将被适当地填充。

    【讨论】:

      【解决方案2】:

      尝试在您的代码中使用 setlocal enabledelayedexpansion。然后使用“!变量!”访问您的变量而不是“%variable%”。 还要确保 %%A 是否正在获取所需的令牌。

      【讨论】:

        【解决方案3】:

        echo 应与if 在同一行:

        if '%Result%'=='this is where the word string shows up' echo Success > %homepath%\Desktop\Success.txt
        

        或用括号括起来:

        if '%Result%'=='this is where the word string shows up' (
            echo Success > %homepath%\Desktop\Success.txt
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-19
          • 2011-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多