1

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?

3
  • 2
    This errormessage is indeed output on STDOUT. (I agree, it should be on STDERR, but in the end, it is (or better was) the developer's choice.) Commented Apr 7, 2022 at 8:59
  • ping is strange in more than this issue. If you ping a non-existent IP in your local network, you get something like "reply from <localhost>: destination not reachable", which is a positive reply (although not from the pinged host) and %errorlevel% gives 0, indicating "success". Commented Apr 7, 2022 at 9:02
  • Maybe I should mentioned that I've also tried with forcing 'Access denied' error (attempt to write to read-only file) and with copying not existing file - all ends up like above. Commented Apr 7, 2022 at 9:52

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Is this the same case with the mentioned above copy and echo (to the restricted file)?
no, it simply stores the original stdout result in a temp file, the errorlevel or exitcode then gets evaluated by the conditional operators and we simply force the output to the file based on the exit code.
0

Simple answer:

@echo off
ping somehost >[file]

It works on Windows 10 and Windows 11.

2 Comments

(don't use 2> instead!)
(also don't use 2>>) i've used .bat extension.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.