【问题标题】:Batch nested for loops returns incorrect value批量嵌套的 for 循环返回不正确的值
【发布时间】:2017-05-14 12:07:38
【问题描述】:

我的脚本中的问题是索引目录文件时的返回值。 首先,我需要循环我的数组,其次是在目录中查找文件。返回值仍然没有变化,并显示所有变量中的最新值。 是的,我知道,这可能是因为我使用 setx 但仅使用 set 绝对不能正常工作。

for /L %%G in (1,1,%i%) do (
  if NOT {arch}=={32} (
    setx DriverPath !DefaultPath!driver\!DriverPath64[%%G]! >nul 2>&1
  ) else (
    setx DriverPath !DefaultPath!driver\!DriverPath32[%%G]! >nul 2>&1
  )

  :: looking for inf file
  for /r "%DriverPath%\" %%f in (*.inf) do (
    set PrinterDriverInf[%%G]=%%f
  )
)

【问题讨论】:

  • 你的意思是if NOT语句中的%arch%吗?(字符串arch不等于字符串32)你是否添加了setlocal enableDelayedExpansion before the for`循环?

标签: windows batch-file for-loop nested-loops


【解决方案1】:
  1. 您为什么使用setx?普通的set 命令不够用吗?请注意,setx 不会更改当前 cmd 实例的变量。
  2. if not 语句将始终计算为 True,因为您在 == 的任一侧都声明了文字字符串。你的意思是%arch% 而不是arch
  3. 您需要延迟扩展 !DriverPath!。但是for /R不能使用延迟扩展变量,所以必须将for /R循环移动到一个子例程中才能使用立即%-expansion,或者你暂时切换到目录让for /R默认到那个(改变的)当前目录。
  4. 切勿在括号中的块中使用:: cmets,而是使用rem

这里是固定代码:

setlocal EnableDelayedExpansion
for /L %%G in (1,1,%i%) do (
    if not "%arch%"=="32" (
        setx DriverPath !DefaultPath!driver\!DriverPath64[%%G]! >nul 2>&1
        set "DriverPath=!DefaultPath!driver\!DriverPath64[%%G]!"
    ) else (
        setx DriverPath !DefaultPath!driver\!DriverPath32[%%G]! >nul 2>&1
        set "DriverPath=!DefaultPath!driver\!DriverPath32[%%G]!"
    )
    rem looking for inf file
    call :SUB PrinterDriverInf[%%G] "%DriverPath%"
)
endlocal
goto :EOF

:SUB    
    for /R "%~2" %%f in (*.inf) do (
        set "%~1=%%f"
    )
    goto :EOF

您甚至可以像这样简化代码:

setlocal EnableDelayedExpansion
if not "%arch%"=="32" set "arch=64"
for /L %%G in (1,1,%i%) do (
    setx DriverPath !DefaultPath!driver\!DriverPath%arch%[%%G]! >nul 2>&1
    set "DriverPath=!DefaultPath!driver\!DriverPath%arch%[%%G]!"
    rem looking for inf file
    pushd "!DriverPath!" && (
        for /R %%f in (*.inf) do (
            set "PrinterDriverInf[%%G]=%%f"
        )
        popd
    )
)
endlocal

【讨论】:

    【解决方案2】:

    :: 评论更改为传统的rem 评论。

    :: 实际上是一个损坏的标签,标签(损坏或其他)会导致代码块出现问题(带括号的语句序列)

    【讨论】:

      【解决方案3】:

      另一件事(我猜)是您试图比较字符串 {arch}{32}

      这是命令解析器看到的:

      if the string {arch} equals {32}, do something

      我猜你想要这个:

      if the content of arch variable equals 32, do something

      如果是这样,这将是你的命令。

      if "%arch%"=="32" echo your commands here
      

      始终使用引号 " 而不是 {},因为它们更安全。

      【讨论】:

      • 哦,是的,我忘了 %% 但这没问题
      • %arch%arch 是两个不同的东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      相关资源
      最近更新 更多