简体   繁体   中英

How to make two batch file variables echo into a single line?

I am trying to create backup script for my ESXi server and I am running in a bit of an issue.

I need to loop these 2 commands and then write them to a text file I call backup.list. It will contain all of the VM IDs and VM names I need to back.

When I have the two loop commands run against the server they only return the last value, I know there is something I am missing but I am not very wise even to batch.

Here is the code:

@ECHO OFF
SET PLINK=C:\Plink.exe
SET ESXHOST=esx01.example.com
SET USERNAME=root
SET PASSWORD=password
SET DATASTORE=/vmfs/volumes/datastore3
IF EXIST Backup.list DEL Backup.list
TYPE NUL>Backup.list
SETLOCAL EnableDelayedExpansion
FOR /F "SKIP=1 TOKENS=1" %%A IN ('%PLINK% %USERNAME%@%ESXHOST% -pw %PASSWORD% vim-cmd vmsvc/getallvms') DO SET ID=%%A
FOR /F "SKIP=1 TOKENS=2" %%B IN ('%PLINK% %USERNAME%@%ESXHOST% -pw %PASSWORD% vim-cmd vmsvc/getallvms') DO SET VM=%%B
ECHO !ID!:!VM!
PAUSE

You need a single loop

FOR /F "SKIP=1 TOKENS=1,2" %%A IN ('%PLINK% %USERNAME%@%ESXHOST% -pw %PASSWORD% vim-cmd vmsvc/getallvms') DO (
SET ID=%%A
SET VM=%%B
ECHO !ID!:!VM!
)

FOR command only loops through the single statement after DO - you need the bracket to tell it that it's a compound statement. Also, the assignment to %%B happens automatically after the first token is stuffed into %%A

You should probably also omit SETLOCAL EnableDelayedExpansion and do directly

FOR /F "SKIP=1 TOKENS=1,2" %%A IN ('%PLINK% %USERNAME%@%ESXHOST% -pw %PASSWORD% vim-cmd vmsvc/getallvms') DO ECHO %%A:%%B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM