问题
I'm using net use
command in batch file to connect a remote location.
I want to store the output of it into a variable and process it.
When the command completes successfully, my code works fine.
However, if there is some error, like wrong password, then I'm not able to store the error output in a variable. It directly prints to the console window in which script is running. Please help with the following:
- Why does this happen?
Why I'm unable to store output in variable when error occurs in the command output? - Is there a suitable way to log ERROR output of the 'net use' command?
Following is my code:
: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
)
)
回答1:
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 '
in a separate command process started with cmd.exe /C
in the background.
The solution is using 2>&1
as Microsoft explains in article about Using Command Redirection Operators.
The two 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.
来源:https://stackoverflow.com/questions/45760676/how-to-process-net-use-command-error-output-in-batch-file-with-a-for-loop