我有一个问题,我需要将一台虚拟机克隆到多台机器上进行生产。 机器的名称由variables分配,而rdp端口也由variables分配。 在脚本结尾处,这两个variables都增加1。 我的问题是,我不知道如何循环创build机器,并增加variables值的代码,直到%M%值在一个定义的数字。
这是我现在的代码:
SET VBoxManage="C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" SET M=1 SET P=25553 if %%M < 4 ( %VBoxManage% clonevm Win2012 --mode all --name M%M% --register %VBoxManage% modifyvm M%M% --vrde on --vrdeauthtype null --vrdemulticon on --vrdeport %P% SET /AM=%M%+1 SET /AP=%P%+1 ECHO Done ECHO %M% ECHO %P% ) ECHO All cloning finished. pause
我已经尝试了FOR,IF和WHILE,但我无法弄清楚如何让它工作。
FOR如何看起来像:
SET VBoxManage="C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" SET M=1 SET P=25553 FOR /L (if %%M IN (1,1,5) ( %VBoxManage% clonevm Win2012 --mode all --name M%M% --register %VBoxManage% modifyvm M%M% --vrde on --vrdeauthtype null --vrdemulticon on --vrdeport %P% SET /AM=%M%+1 SET /AP=%P%+1 ECHO Done ECHO %M% ECHO %P% ) ECHO All cloning finished. pause
我想你只需要检查FOR /? 帮助一下。 你混合了一些不同的东西在一起,这是行不通的。 与您可能熟悉的其他脚本环境相比, cmd解释器是有限的 。
我想所有你问的是:“如何在一个batch file中使用FOR ,以1为增量从1到5进行计数? 这很简单:
FOR /L %%M IN (1, 1, 5) DO ( ECHO %%M )
你的问题的第二部分是增加FOR循环内的另一个variables。 为此,您需要查找SETLOCAL EnableDelayedExpansion 。 这是使用您提供的脚本的一个例子。
@ECHO OFF SETLOCAL EnableDelayedExpansion SET VBoxManage="C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" SET P=25553 FOR /L %%M IN (1, 1, 5) DO ( %VBoxManage% clonevm Win2012 --mode all --name M%%M --register %VBoxManage% modifyvm M%%M --vrde on --vrdeauthtype null --vrdemulticon on --vrdeport !P! SET /AP=P + 1 ECHO Done ECHO %%M ECHO !P! ) ECHO All cloning finished. PAUSE
为了逃避EnableDelayedExpansion,你可以尝试下一个过程调用的方法:
@ECHO OFF >NUL setlocal SET "VBoxManage=C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" SET /A "P=25553" FOR /L %%M IN (1,1,5) Do call :treat %%M ECHO All cloning finished. pause endlocal goto :eof :treat rem next two operational commands are ECHO-ed for debugging purposes echo "%VBoxManage%" clonevm Win2012 --mode all --name M%~1 --register echo "%VBoxManage%" modifyvm M%~1 --vrde on --vrdeauthtype null --vrdemulticon on --vrdeport %P% ECHO Done M=%~1 P=%P% SET /A "P+=1" goto :eof
下一个源(FOR)和SET