Reputation: 25
I have a simple health check script for checking status of windows share drives listed below.
I am getting the desired output when the command works. However, when there is an error, I do not get output in the output file. I have looked at STDOUT and STDERR as a possible solution, but I am not able get this to work yet.
Can anyone please help me with this code.
@echo off
echo START > results.txt
for /f %%s in (server_list.txt) do (
echo %%s >> results.txt
for /f "delims=" %%n in ('net use \\%%s') do (
echo %%s - %%n >> results.txt 2> err.txt
)
)
The output file looks like this.
START
server1
server1 - The command completed successfully.
server2
server2 - The command completed successfully.
However, there is nothing in the err.txt
file. I have made sure to put some incorrect entries in file server_list.txt
to get a few errors for testing. The error output is displayed in the command line window instead of being printed to the err.txt
file.
Upvotes: 0
Views: 1300
Reputation: 49086
First, read the Microsoft article about Using Command Redirection Operators.
Second, the command FOR executes the command line net use \\%%s
in a new command process using cmd.exe
in background which means with no visible console window. The output of this background command process written to STDOUT is captured by FOR and processed next line by line. The error output written to STDERR is redirected by FOR to error output of currently running process which is the reason why the error output can be seen in opened console window of command process executing the batch file.
The command line echo %%s - %%n >> results.txt 2> err.txt
outputs the output of background command process executing net use
captured by FOR and assigned to loop variable n
to STDOUT of current command process which is redirected to file results.txt
.
Additionally the error output by command ECHO is redirected to file err.txt
if ECHO would output an error message. But ECHO does never output an error message. That is the reason why err.txt
does not contain any error message output by command NET.
I suggest to capture with FOR standard and error output of net use
and evaluate the output in body of FOR loop.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
del err.txt 2>nul
echo START > results.txt
for /F %%I in (server_list.txt) do (
for /f "delims=" %%J in ('%SystemRoot%\System32\net.exe use "\\%%I" 2^>^&1') do (
set "NetOutput=%%J"
if not "!NetOutput:successfully=!" == "!NetOutput!" (
echo %%I - %%J>>results.txt
) else (
echo %%I - %%J>>err.txt
)
)
)
endlocal
When the line output by command NET from any output contains the word successfully
the line from server_list.txt
and the success message is written to file results.txt
. Otherwise the most likely error output is written also with line from server_list.txt
to file err.txt
.
Upvotes: 1