The thing is that redirecting errors to the file in command line doesn't work. I will explain this by giving an example.
ping /wrong > output.txt 2> error.err
produces empty error.err file and output.txt with error text . That's huge surprice since this synthax is given in MS docs and literally everywhere over the web.
Using >>
instead of >
with 2>>
instead of 2>
doesn't change command line behaviour. I've also tried running it as script with .cmd
extension, running with command line in admin mode and none of this help.
Moreover, ping /wrong 2> error.err
ends up with error apearing in console (which doesn't happened in previous example since it was redirected). Any thoughts?
CodePudding user response:
ping
being a diagnostics tool, only always sends results to stdout
stream because of, seemingly, that very reason (Developers choice as stated by @Stephan).
The end result however will set an exitcode
of off the errorlevel
which can be used accordingly if required.
So given this known example:
ping somehost && echo Success || echo Failed
Would use the errorlevel
to determine the correct path, either it was successfully, or it failed. So you can simply utilize that ability to perform a little hack:
ping somehost >hold.tmp && type hold.tmp>output.txt || type hold.tmp>error.err
del /Q hold.tmp>nul 2>&1
CodePudding user response:
Simple answer:
@echo off
ping somehost >[file]
It works on Windows 10 and Windows 11.