尝试理解这段代码(批处理,CMD)

4
    @echo off
setlocal enabledelayedexpansion
::just a sample adapter here:
set "adapter=Ethernet adapter Local Area Connection"
set adapterfound=false
echo Network Connection Test
for /f "usebackq tokens=1-2 delims=:" %%f in (`ipconfig /all`) do 
(
    set "item=%%f"
    if /i "!item!"=="!adapter!" 
  (
        set adapterfound=true
      )
   else if not "!item!"=="!item:IP Address=!" if "!adapterfound!"=="true" 
  (
        echo Your IP Address is: %%g
        set adapterfound=false
      )
)

我对batch很陌生,请问以下几个问题:

  1. 在这种情况下,setlocal enabledelayedexpansion是什么作用?
  2. usebackq是什么意思? (我尝试过查找但没有完全理解)
  3. 变量%%g是如何初始化的,并且它是全局还是局部的?

谢谢您的时间!


实际上,脚本无法工作,因为存在一些语法错误:for ... do (if ... () else(括号不能单独放在一行中!) - aschipfl
1
我建议阅读Stack Overflow批处理文件文档页面 - SomethingDark
1个回答

2
  1. Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
    Code below would seem to echo second second, but it prints first second instead.

     setlocal EnableDelayedExpansion
     set var=first
     set var=second & Echo %var% !var!
    

    Source: SS64

  2. usebackq forces for loops use backquotes (`dir`) to evaluate the commands inside it and use the output for the forloop, instead of open a file. This will list all elements of Documents predeced with an asterisk.

    echo Documents:
    for /f "usebackq" %%i in (`dir /b "C:\Users\%username%\Documents\"`) do (
      echo * %%i
    )
    pause
    
  3. They're local. Using the previous example, %%iis defined just in the for loop, no additional initialization needed.


我仍然不明白%%g变量是如何被初始化为IP地址的,这是如何工作的,我该如何将其存储在全局变量中?此外,延迟扩展有什么好处,为什么这个人决定像这样实现代码?总之,对所有内容的解释都很好,谢谢! - user7253664
如果没有setlocal enabledelayedexpansion,则item变量在循环完成之前将没有值,因为它是在for循环内部初始化的。 %%g是由循环的tokens=1-2部分创建的。该部分声明了两个变量,并且由于您从%%f开始,具有下一个最高ASCII值的字符是%%g。我不知道为什么要使用usebackq;除了个人喜好外,没有理由存在。 - SomethingDark
我仍然没有看到它如何获得它的值。第一次提及它只是回显。 - user7253664

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接