如何处理带有FOR循环的批处理文件中的"net use"命令错误输出? [英] How to process 'net use' command error output in batch file with a FOR loop?
问题描述
我正在批处理文件中使用net use
命令来连接远程位置.
我想将其输出存储到变量中并进行处理.
命令成功完成后,我的代码可以正常工作.
但是,如果出现一些错误(例如密码错误),那么我将无法将错误输出存储在变量中.它直接打印到运行脚本的控制台窗口.请提供以下帮助:
- 为什么会这样?
为什么在命令输出中出现错误时,我无法将输出存储在变量中? - 是否有适当的方法来记录"net use"命令的ERROR输出?
以下是我的代码:
:connNEWlocation
echo Connecting required remote location...
for /f "tokens=1,2,3,4,5,6,7,8 delims=*" %%a IN ('net use \\!hostaddress!\!user! /user:!user! !user_pass!') DO (
if "%%a"=="The command completed successfully." (
echo Connected successfully^!
) else (
echo ERROR:"%%a"
echo do something based on error obtained here
)
)
将错误输出写入以处理 STDERR (标准错误).但是 FOR 仅捕获为处理 STDOUT 而编写的标准输出,该输出是在以cmd.exe /C
为背景的单独命令过程中在两个'
之间运行命令行的./p>
该解决方案使用的是
The error output is written to handle STDERR (standard error). But FOR captures only standard output written to handle STDOUT on running the command line between the two The solution is using The two operators 这篇关于如何处理带有FOR循环的批处理文件中的"net use"命令错误输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!2>&1
,正如Microsoft在有关'
in a separate command process started with cmd.exe /C
in the background.2>&1
as Microsoft explains in article about Using Command Redirection Operators.>
and &
must be escaped in this case with caret character ^
to be interpreted first as literal characters on parsing the entire FOR command line by Window command processor before the FOR command line is executed at all.for /F "delims=" %%a in ('net use \\!hostaddress!\!user! /user:!user! !user_pass! 2^>^&1') do (
"delims="
disables splitting up the captured line(s) into tokens using space and horizontal tab character as delimiters because it defines an empty list of delimiters.