Windows 批处理变量不会设置

标签 windows batch-file if-statement cmd delayedvariableexpansion

我想我在 Window 的批处理脚本中遇到了一个错误。

我无法设置扩展 if 语句中的变量。

这是我的脚本的一个单独部分:

@echo off

set success=1
set Version=12345
set Target=Client
set Type=456
set dir=
set zip=

if "%Version%"=="" set success=0
if "%Type%"=="" set success=0

if 1==1 set test=42

if %success%==1 (
    set test2=57005
    if "%Target%"=="Client" (
        set dir=ModName v%Version%
        set zip=ModName v%Version% %Type%.zip
        echo Version: %Version%
        echo    Type: %Type%
        echo.
        echo  Target: %Target%
        echo     dir: %dir%
        echo     zip: %zip%
        echo.
        echo    test: %test%
        echo   test2: %test2%
    )
) else (
    echo Not successful.
)

这是一个全新的 cmd 实例的输出:

C:\Users\RandomClown\Desktop>test.bat
Version: 12345
   Type: 456

 Target: Client
    dir:
    zip:

   test: 42
  test2:

您应该注意到单行 if 语句正确设置了内容。 多行 if 将执行任何不是集合的操作。我不认为我错过了什么。 此外,多行 if 语句正确执行了正确的行,因为 else ( echo Not success. ) 行未执行。

为什么这些行没有执行?

最佳答案

你错过了一些东西;-)

cmd 在解析命令时扩展变量,而不是在运行命令时扩展变量。碰巧,带有 block ( ... ) (或实际上任何 block )的 iffor 语句被视为单个命令那种情况。因此,当您在 block 内设置变量并尝试在同一个 block 中使用它们时,就不再有变量了——它们被变量在 block 执行之前所具有的值所取代.

贴一个

setlocal enabledelayedexpansion

在批处理文件的开头并使用 !zip! 而不是 %zip%。有关问题的详细讨论,请参阅帮助集

关于Windows 批处理变量不会设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9681863/

相关文章:

java - (CMD) 退出后我想做点什么

c - C 语言编程中求两个整数的倍数

windows - 巴布恩 : copy/paste from windows clipboard into vim?

windows - C++11 std::cout << "string literal in UTF-8"到 Windows cmd 控制台? ( Visual Studio 2015)

batch-file - “ls”不被识别为内部或外部命令、可操作程序或批处理文件

windows - 在 Windows 批处理中用双引号“比较一个字符

c++ - boolean 运算在 C++ 类内部重载以及类内日期的 if 语句

带有 if else 语句的 Java Scanner 输入

Windows 内核驱动程序签名和服务创建

windows - 在 Windows 上,WSASend 失败并显示 WSAENOBUFS