windows - 嵌套 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%
解决方案
您尝试在被调用的 sub-routine 中访问for
-loop 元变量,但失败了。你可以:%%a
:compare
%%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
语法,它保护特殊字符并避免无意的尾随空格。%%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%
推荐阅读
- python - Ironpython 中的凸壳
- gitlab - 无法创建 GitLab PipeLine(未定义错误)
- scala - 使用 Scala 提取嵌入式 AWS Glue 连接凭证
- python - 如何为总和的每个术语写评论?
- ios - Xcode 12 Beta:同一项目中的框架“没有这样的模块”
- angular - 角度变量未刷新(未在模板中正确显示)
- python - 根据分隔符拆分字符串但跨 1
- java - 在 Java 中使用哨兵对象实现红黑树时出错
- javascript - 如何制作一个能够响应页面生成的声音的音频可视化工具
- c# - Http GET 方法返回编码错误的文件内容