当我第一次开始尝试构建它时,作为一种保留 IP 地址变量的外部文件的方式,因此我只需要编辑一个列表,我觉得我做错了什么。但后来它奏效了。但是它也输出The system cannot find the drive specified
在“IP”和“名称”之间。当我更改为,时,这停止了(代码已更新)::
rem
我的目标是在此基础上进行大量自动部署和维护,例如调用 pscp/plink (PuTTY) 和写入日志文件,例如Deploying on [name] xxxx
. 这是编写此代码的一种健壮/适当的方式吗?对我来说,它感觉出奇的干净。
我可以检查:正在使用!xxx!
延迟扩展吗?如果是这样,您是否应该始终将变量包装起来以!
进行延迟扩展?(我阅读了 Windows 批处理文件:什么是变量扩展,EnableDelayedExpansion 是什么意思?但我并不是 100% 清楚!
这是导致这种情况的原因。)
这个叫什么?我是否使用变量值作为变量的名称,是否有一个计算机科学术语?是评估吗?
@echo off
setlocal EnableDelayedExpansion
set ips[0]=192.168.0.1
set 192.168.0.1=router
set ips[1]=192.168.0.2
set 192.168.0.2=printer
set ips[2]=192.168.0.3
set 192.168.0.3=nas
for /F "tokens=2 delims==" %%a in ('set ips[') do (
rem the next line outputs the IP as it is evaluating the dynamic
rem variable being temp created with the for loop
echo IP is %%a
rem with delayed expansion set (see top) we can use the value
rem of the IP that is being used with the for loop
rem and further lookup by essentially evaluating again
echo Name of IP is !%%a!
)
pause
结果:
IP is 192.168.0.1
Name of IP is router
IP is 192.168.0.2
Name of IP is printer
IP is 192.168.0.3
Name of IP is nas
Press any key to continue . . .
将IP阵列放入外部文件
所以继续编辑的代码(上面反映的编辑),我现在尝试将 IP 数组移动到一个外部文件中并调用它,它给出了Environment variable ips[ not defined
演示.bat:
@echo off
setlocal EnableDelayedExpansion
call info_IPs.bat
for /F "tokens=2 delims==" %%a in ('set ips[') do (
rem the next line outputs the IP as it is evaluating the dynamic
rem variable being temp created with the for loop
echo IP is %%a
rem with delayed expansion set (see top) we can use the value
rem of the IP that is being used with the for loop
rem and further lookup by essentially evaluating again
echo Name of IP is !%%a!
)
pause
info_IPs.bat:
@echo off
setlocal EnableDelayedExpansion
set ips[0]=192.168.0.1
set 192.168.0.1=router
set ips[1]=192.168.0.2
set 192.168.0.2=printer
set ips[2]=192.168.0.3
set 192.168.0.3=nas