简体   繁体   中英

Capture the Output of “Move” Command into a variable in batch

I am trying to run a move command inside a batch file. I have pretty much made it worked fine using this...

Move /Y "%1\%2 %3" %4 >nul
:: and this for decision making and logging...
if %errorlevel%==0 GOTO DONE
if %errorlevel%==1 GOTO FAILED 

Note: %1-4 are variables i am passing over from another batch file that are basically the original path of the file, the file name and new path.

But i would like to capture the output of the command into a variable for writing to a log and decision making within the same batch... The output i am referring to is the 1 file(s) moved. when successful or the The network path was not found. when it can't find the file or any other message for that matter

Up to this point i have tried this...

for /f "tokens=*" %%a in ('Move /Y "%1\%2 %3" %4') do set FailReason=%%a

and even when the move still works... I can't capture the outputs listed above...

Any help would be greatly appreciated. Thanks in advance.

This will let you get the STDERR as well as STDOUT into a variable:

@echo off
for /f "delims=" %%a in ('Move /Y "%1\%2 %3" %4 2^>^&1 ') do echo %%a
@ECHO OFF
SETLOCAL
SET "sourcedir=c:\sourcedir"
SET "destdir=c:\destdir"

DEL "%destdir%\test*">NUL 2>nul
FOR /l %%i IN (1,1,4) DO COPY /y NUL "%sourcedir%\testfile %%i.txt" >nul
COPY /y NUL "%destdir%\testfile 2.txt" >NUL
COPY /y NUL "%destdir%\testfile 4.txt" >NUL
ATTRIB +r "%destdir%\testfile 4.txt"

:: 5 tests - OK, destfile exists, destfile R/O, sourcefile not found, sourcedir does not exist


CALL :testmove %sourcedir% testfile 1.txt %destdir%
CALL :testmove %sourcedir% testfile 2.txt %destdir%
CALL :testmove %sourcedir% testfile 4.txt %destdir%
CALL :testmove %sourcedir% testfile 5.txt %destdir%
CALL :testmove \unknowndir testfile 5.txt %destdir%

ATTRIB -r "%destdir%\testfile 4.txt"
GOTO :eof

:testmove
FOR /f "delims=" %%i IN ('Move /Y "%1\%2 %3" %4 2^>^&1') DO SET reason=%%i
ECHO %* produced ERRORLEVEL %ERRORLEVEL% and reason %reason%

GOTO :EOF

ERRORLEVEL always appears to be 0 though...

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