Reputation: 461
set machines=PC2 TEST-PC PC34
for %%a in (%machines%) do (
echo %%a
echo.
) > PCs.txt
I want to loop through a list of machines and execute code for each machine. But in my PCs.txt there is only one line with PC34.
What's my mistake?
Thanks in advance!
Upvotes: 0
Views: 56
Reputation: 70923
The problem is the redirection operator. It will overwrite the file if it exist and create it if it does not exist. But as it is written, the operation is executed for each of the iterations of the loop.
You have two options. The first one is
type nul > pcs.txt
for %%a in (%machines%) do (
echo %%a
echo.
) >> pcs.txt
First create/empty the file and then append data to it. But this will open the file once for each iteration to add the data.
The second option is
(for %%a in (%machines%) do (
echo %%a
echo.
)) > pcs.txt
That is, instead of opening and writting in each iteration, do it only once for the full for
loop.
Upvotes: 1
Reputation: 41474
The loop is working properly; the only problem is that redirection to a file overwrites the file if it already exists. To append instead, use the >>
redirection operator. (Clear the file beforehand to get rid of any existing content.) Like so:
set machines=PC2 TEST-PC PC34
copy /Y NUL: PCs.txt
for %%a in (%machines%) do (
echo %%a
echo.
) >> PCs.txt
Upvotes: 2