0

I am writing a Batch-script which copies a file to multiple servers. It takes the servername from a .txt file as a variable and uses it to connect to the server.
After a name was turned into a variable, I want to remove this entry from the file (and save it to another file) so that the Script takes the next available server name when running again.

So far, I have written this:

@echo off
:start
set /p servername=<server.txt
findstr /v "%servername%" server.txt > serverdone.txt

rem (Part of the script that copies the file, this is already working)

GOTO start

The script is able to take the first line of server.txt and puts it in the %servername% variable as supposed, however, the findstr line does not seem to work. The serverdone.txt file stays empty, and the script just keeps using the first server in the server.txt file. I used this question as a guide: Delete certain lines in a txt file via a batch file.

Community
  • 1
  • 1
Spypsyduck
  • 115
  • 5

1 Answers1

1

Why do you not use a for /F loop to read the file server.txt line by line and do the copying stuff within that loop? I think this could perfectly work for you. Take a look at the following example:

@echo off

rem This iterates through all lines of `server.txt`:
for /F "usebackq delims=" %%S in ("server.txt") do (

    rem Call copying sub-routine for each item:
    call :SUB_COPY %%S

)
exit /B

:SUB_COPY
rem (do your copying stuff here, using `%1`)
exit /B

The copying stuff could also be placed within the for /F loop directly (using %%S instead of %1).


In case the copying stuff could fail and you want server.txt to contain all server names for which it failed and serverdone.txt to contain those for which it succeeded, you could do this:

@echo off

rem This iterates through all lines of `server.txt`;
rem `type` ensures the file to be read completely
rem before the any further activities are pursued;
rem `break` does nothing and is used to empty files:
for /F "delims=" %%S in ('
    type "server.txt" ^& ^
        ^> "server.txt" break ^
        ^> "serverdone.txt" break
') do (

    rem Call copying sub-routine for each item:
    call :SUB_COPY %%S
    if ErrorLevel 1 (
        rem (`ErrorLevel` is `>=1`, so failure)
        >> "server.txt" echo %%S
    ) else (
        rem (`ErrorLevel` is `0`, so success)
        >> "serverdone.txt" echo %%S
    )

)
exit /B

:SUB_COPY
rem (do your copying stuff here, using `%1`;
rem  in case of errors, set `ErrorLevel`)
exit /B 0 & rem (success: `ErrorLevel` is `0`)
exit /B 1 & rem (failure: `ErrorLevel` is `1`)
aschipfl
  • 33,626
  • 12
  • 54
  • 99