将“移动”命令的输出捕获到批处理变量中

时间:2013-10-03 04:10:08

标签: windows batch-file

我正在尝试在批处理文件中运行move命令。 我几乎用它做得很好......

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

注意:%1-4是我从另一个批处理文件传递的变量,它们基本上是文件的原始路径,文件名和新路径。

但我想将命令的输出捕获到一个变量中,以便写入日志并在同一批次内做出决策...... 我指的输出是 移动了1个文件。什么时候成功 或者 找不到网络路径。什么时候找不到文件 或任何其他消息

到目前为止,我已经尝试过这个......

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

即使此举仍然有效...... 我无法捕捉上面列出的输出......

非常感谢任何帮助。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

这将让您将STDERR以及STDOUT变为变量:

@echo off
for /f "delims=" %%a in ('Move /Y "%1\%2 %3" %4 2^>^&1 ') do echo %%a

答案 1 :(得分:0)

@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似乎总是为0 ......

相关问题