How to process 'net use' command error output in batch file with a FOR loop?

℡╲_俬逩灬. 提交于 2020-01-03 20:56:29

问题


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:

  1. Why does this happen?
    Why I'm unable to store output in variable when error occurs in the command output?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!