首页 > 解决方案 > 嵌套 for 循环:使用批处理脚本将当前屏幕分辨率存储为各种远程机器的变量

问题描述

我需要获取每台远程机器的当前屏幕分辨率(相同的 IP 存储在 .txt 文件中)并将其作为变量存储在脚本中以供进一步使用。

我能够遍历 .txt 文件中的机器,并且能够将屏幕分辨率存储为变量,但我无法在所有机器的循环中执行此操作。谁能告诉我哪里出错了?如何在后面的代码中使用 use %%a set in first for 以及 next for 循环?

Set MyFile=VMs.txt
rem VMs.txt contains IPs of the machines

for /f "usebackq delims=" %%a in ("%MyFile%") do call :compare
    
:compare
for /f "tokens=2 delims==" %%i in ('wmic /node:"%%a" path Win32_VideoController get CurrentVerticalResolution /value ^| find "="') do set height=%%i
echo %height% 

标签: windowsfor-loopbatch-filecmdmethod-call

解决方案


您尝试在被调用的 sub-routine 中访问for-loop 元变量,但失败了。你可以:%%a:compare

  1. %%a作为参数传递给子例程并通过那里访问它%1

     Set "MyFile=VMs.txt"
     rem VMs.txt contains IPs of the machines
    
     for /f "usebackq delims=" %%a in ("%MyFile%") do call :compare %%a
     goto :EOF
    
     :compare
     for /f "tokens=2 delims==" %%i in ('wmic /node:"%~1" path Win32_VideoController get CurrentVerticalResolution /value ^| find "="') do set "height=%%i"
     echo(%height%
    

    ~-character in确保传递的%~1参数不被引用(尽管在这里可能不需要),因此表达式 周围只有一对引号"%~1"

    注意 command ,它可以防止之后的代码在第一个循环完成goto :EOF时无意中执行。for /f

    还要注意引用的set语法,它保护特殊字符并避免无意的尾随空格。

  2. %%a或者确保包含在循环体中的子例程中的代码运行for,因为for元变量是全局的,但它们只能在循环for上下文中访问,这不再适用于子例程,即使调用来自循环体。

    要在子例程中重新建立循环上下文,只需将相关代码放在for只迭代一次的循环中:

     Set "MyFile=VMs.txt"
     rem VMs.txt contains IPs of the machines
    
     for /f "usebackq delims=" %%a in ("%MyFile%") do call :compare
     goto :EOF
    
     :compare
     for %%j in (.) do for /f "tokens=2 delims==" %%i in ('wmic /node:"%%a" path Win32_VideoController get CurrentVerticalResolution /value ^| find "="') do set "height=%%i"
     echo(%height%
    

推荐阅读