Lup Gabriel
Lup Gabriel

Reputation: 39

Copy command output result to variable batch

So I'm trying to copy a local file to my network using batch scripting and would like to be able to get a result to know if the process completed properly.

My code is below:

@echo off
set locatie_folder=G:\Info\instructiuni.mht
for /f "tokens=1,2 delims= " %%a in (IP.txt) do (
    copy %locatie_folder% "\\%%a\vsr">> temp.tmp
    set /p VAR=<temp.tmp
    echo %%b %VAR%
    del temp.tmp
)
pause
exit

My IP.txt file looks like so:

10.117.14.10 100-01
10.117.14.11 100-02
10.117.14.12 100-03

First is the IP and second is a dedicated name for that IP in the network.

I need to output something like

100-01 1 file(s) copied.
100-02 0 file(s) copied.
100-03 1 file(s) copied.

Now my problem is that for some reason the variable VAR is not getting me the status "0 file(s) copied." or "1 file(s) copied." while reading even if it writes properly in the temp.tmp file.

What am I doing wrong here?

Upvotes: 0

Views: 1512

Answers (2)

Squashman
Squashman

Reputation: 14320

Put your COPY command inside a FOR /F command to capture the verbose output to a variable. Something like this.

for /F "tokens=* delims= " %%G in ('copy temp.txt C:\temp\') do echo %%b %%G

Edit: with your exact code.

@echo off

set locatie_folder=G:\Info\instructiuni.mht

for /f "tokens=1,2 delims= " %%a in (IP.txt) do (
    for /F "tokens=* delims= " %%G in ('copy %locatie_folder% "\\%%a\vsr"') do echo %%b %%G
)
pause
exit

Upvotes: 1

aschipfl
aschipfl

Reputation: 34979

You need to enable delayed expansion for getting the new value of VAR, because you are setting and reading it within a block of code (the for loop). The immediate %VAR% expansion always returns the value when the entire block of code is parsed; with delayed !VAR! expansion, you will get the updated value.

Try this:

@echo off
setlocal EnableDelayedExpansion

set "locatie_folder=G:\Info\instructiuni.mht"

for /F "usebackq tokens=1,2 delims= " %%A in ("IP.txt") do (
    > "temp.tmp" copy "%locatie_folder%" "\\%%~A\vsr"
    < "temp.tmp" set /P VAR=
    echo "%%~B" !VAR!
    del "temp.tmp"
)
pause
endlocal
exit /B

You can make it all even simpler though, without using a temporary file, when you let another for /F loop capture the output of the copy command:

@echo off

set "locatie_folder=G:\Info\instructiuni.mht"

for /F "usebackq tokens=1,2 delims= " %%A in ("IP.txt") do (
    for /F "delims=" %%X in ('copy "%locatie_folder%" "\\%%~A\vsr"') do (
        echo "%%~B" %%X
    )
)
pause
exit /B

Upvotes: 2

Related Questions