Windows cmd redirect output to file

I'm trying to redirect all output (stdout + stderr) of a Windows command to a single file: C:>dir 1> a.txt 2> a.txt The process cannot access the file because it is being used by another

Background info from Microsoft documentation

While the accepted answer to this question is correct, it really doesn’t do much to explain why it works, and since the syntax is not immediately clear I did a quick www search to find out what was actually going on. In the hopes that this information is helpful to others, I’m posting it here.

Taken from the Microsoft documentation page:
Redirecting error messages from Command Prompt: STDERR/STDOUT

Summary

When redirecting output from an application using the > symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.

Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol. This selects the second output stream that is STDERR.

Example

The command dir file.xxx (where file.xxx does not exist) will display the following output:

Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876
File Not Found

If you redirect the output to the NUL device using dir file.xxx > nul, you will still see the error message:

File Not Found

To redirect the error message to NUL, use the following command:

dir file.xxx 2> nul

Or, you can redirect the output to one place, and the errors to another.

dir file.xxx 1> output.msg 2>&1

You can print the errors and standard output to a single file by using the &1 command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:

dir file.xxx 1> output.msg 2>&1

To expand on davor’s answer, you can use PowerShell like this:

powershell "dir | tee test.txt"

If you’re trying to redirect the output of an exe in the current directory, you need to use . on the filename, eg:

powershell ".something.exe | tee test.txt"

Community's user avatar

answered Dec 31, 2013 at 8:59

Saxon Druce's user avatar

Saxon DruceSaxon Druce

17.3k5 gold badges48 silver badges71 bronze badges

12

I was able to find a solution/workaround of redirecting output to a file and then to the console:

dir > a.txt | type a.txt

where dir is the command which output needs to be redirected, a.txt a file where to store output.

Christopher Painter's user avatar

answered Jul 17, 2009 at 6:59

NSPKUWCExi2pr8wVoGNk's user avatar

11

Check this out: wintee

No need for cygwin.

I did encounter and report some issues though.

Also you might check unxutils because it contains tee (and no need for cygwin), but beware that output EOL’s are UNIX-like here.

Last, but not least, is if you have PowerShell, you could try Tee-Object. Type get-help tee-object in PowerShell console for more info.

answered Sep 15, 2012 at 14:57

Davor Josipovic's user avatar

Davor JosipovicDavor Josipovic

5,0681 gold badge37 silver badges55 bronze badges

3

@tori3852

I found that

dir > a.txt | type a.txt

didn’t work (first few lines of dir listing only — suspect some sort of process forking and the second part, the ‘type’ command terminated before the dire listing had completed? ),
so instead I used:

dir > z.txt && type z.txt

which did — sequential commands, one completes before the second starts.

Brian Webster's user avatar

Brian Webster

29.6k48 gold badges150 silver badges224 bronze badges

answered Feb 2, 2011 at 5:25

Andy Welch's user avatar

Andy WelchAndy Welch

5374 silver badges2 bronze badges

1

A simple C# console application would do the trick:

using System;
using System.Collections.Generic;
using System.IO;

namespace CopyToFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            var buffer = new char[100];
            var outputs = new List<TextWriter>();

            foreach (var file in args)
                outputs.Add(new StreamWriter(file));

            outputs.Add(Console.Out);

            int bytesRead;
            do
            {
                bytesRead = Console.In.ReadBlock(buffer, 0, buffer.Length);
                outputs.ForEach(o => o.Write(buffer, 0, bytesRead));
            } while (bytesRead == buffer.Length);

            outputs.ForEach(o => o.Close());
        }
    }
}

To use this you just pipe the source command into the program and provide the path of any files you want to duplicate the output to. For example:

dir | CopyToFiles files1.txt files2.txt 

Will display the results of dir as well as store the results in both files1.txt and files2.txt.

Note that there isn’t much (anything!) in the way of error handling above, and supporting multiple files may not actually be required.

T.S.'s user avatar

T.S.

17.6k11 gold badges57 silver badges78 bronze badges

answered Apr 28, 2009 at 7:01

Richard's user avatar

RichardRichard

1,1696 silver badges8 bronze badges

9

Unfortunately there is no such thing.

Windows console applications only have a single output handle. (Well, there are two STDOUT, STDERR but it doesn’t matter here) The > redirects the output normally written to the console handle to a file handle.

If you want to have some kind of multiplexing you have to use an external application which you can divert the output to. This application then can write to a file and to the console again.

Zombo's user avatar

answered Apr 28, 2009 at 6:48

Daniel Rikowski's user avatar

Daniel RikowskiDaniel Rikowski

70.2k57 gold badges250 silver badges324 bronze badges

1

This works, though it’s a bit ugly:

dir >_ && type _ && type _ > a.txt

It’s a little more flexible than some of the other solutions, in that it works statement-by-statement so you can use it to append as well. I use this quite a bit in batch files to log and display messages:

ECHO Print line to screen and log to file.  >_ && type _ && type _ >> logfile.txt

Yes, you could just repeat the ECHO statement (once for the screen and the second time redirecting to the logfile), but that looks just as bad and is a bit of a maintenance issue. At least this way you don’t have to make changes to messages in two places.

Note that _ is just a short filename, so you’ll need to make sure to delete it at the end of your batch file (if you’re using a batch file).

answered Mar 17, 2011 at 1:49

MTS's user avatar

MTSMTS

1,8232 gold badges17 silver badges15 bronze badges

5

I’d like to expand a bit on Saxon Druce’s excellent answer.

As stated, you can redirect the output of an executable in the current directory like so:

powershell ".something.exe | tee test.txt"

However, this only logs stdout to test.txt. It doesn’t also log stderr.

The obvious solution would be to use something like this:

powershell ".something.exe 2>&1 | tee test.txt"

However, this won’t work for all something.exes. Some something.exes will interpret the 2>&1 as an argument and fail. The correct solution is to instead only have apostrophes around the something.exe and its switches and arguments, like so:

powershell ".something.exe --switch1 --switch2 … arg1 arg2 …" 2^>^&1 ^| tee test.txt

Notice though, that in this case you have to escape the special cmd-shell characters «>&|» with a «^» each so they only get interpreted by powershell.

e.d.n.a's user avatar

answered Jun 18, 2016 at 11:07

アリスター's user avatar

アリスターアリスター

3322 silver badges7 bronze badges

5

mtee is a small utility which works very well for this purpose. It’s free, source is open, and it Just Works.

You can find it at http://www.commandline.co.uk.

Used in a batch file to display output AND create a log file simultaneously, the syntax looks like this:

    someprocess | mtee /+ mylogfile.txt

Where /+ means to append output.

This assumes that you have copied mtee into a folder which is in the PATH, of course.

answered Oct 21, 2011 at 20:36

Mark's user avatar

MarkMark

1811 silver badge2 bronze badges

2

I agree with Brian Rasmussen, the unxutils port is the easiest way to do this. In the Batch Files section of his Scripting Pages Rob van der Woude provides a wealth of information on the use MS-DOS and CMD commands. I thought he might have a native solution to your problem and after digging around there I found TEE.BAT, which appears to be just that, an MS-DOS batch language implementation of tee. It is a pretty complex-looking batch file and my inclination would still be to use the unxutils port.

answered Apr 28, 2009 at 7:06

Steve Crane's user avatar

Steve CraneSteve Crane

4,2405 gold badges38 silver badges63 bronze badges

2

If you have cygwin in your windows environment path you can use:

 dir > a.txt | tail -f a.txt

answered May 16, 2014 at 13:12

jkdba's user avatar

jkdbajkdba

2,2283 gold badges21 silver badges32 bronze badges

2

dir 1>a.txt 2>&1 | type a.txt

This will help to redirect both STDOUT and STDERR

answered Nov 2, 2011 at 15:23

rashok's user avatar

rashokrashok

12.3k15 gold badges86 silver badges99 bronze badges

2

I know this is a very old topic, but in previous answers there is not a full implementation of a real time Tee written in Batch. My solution below is a Batch-JScript hybrid script that use the JScript section just to get the output from the piped command, but the processing of the data is done in the Batch section. This approach have the advantage that any Batch programmer may modify this program to fit specific needs. This program also correctly process the output of CLS command produced by other Batch files, that is, it clear the screen when CLS command output is detected.

@if (@CodeSection == @Batch) @then


@echo off
setlocal EnableDelayedExpansion

rem APATee.bat: Asynchronous (real time) Tee program, Batch-JScript hybrid version
rem Antonio Perez Ayala

rem The advantage of this program is that the data management is written in Batch code,
rem so any Batch programmer may modify it to fit their own needs.
rem As an example of this feature, CLS command is correctly managed

if "%~1" equ "" (
   echo Duplicate the Stdout output of a command in the screen and a disk file
   echo/
   echo anyCommand ^| APATee teeFile.txt [/A]
   echo/
   echo If /A switch is given, anyCommand output is *appended* to teeFile.txt
   goto :EOF
)

if "%2" equ ":TeeProcess" goto TeeProcess

rem Get the output of CLS command
for /F %%a in ('cls') do set "cls=%%a"

rem If /A switch is not provided, delete the file that receives Tee output
if /I "%~2" neq "/A" if exist %1 del %1

rem Create the semaphore-signal file and start the asynchronous Tee process
echo X > Flag.out
if exist Flag.in del Flag.in
Cscript //nologo //E:JScript "%~F0" | "%~F0" %1 :TeeProcess
del Flag.out
goto :EOF

:TeeProcess
   rem Wait for "Data Available" signal
   if not exist Flag.in goto TeeProcess
   rem Read the line sent by JScript section
   set line=
   set /P line=
   rem Set "Data Read" acknowledgement
   ren Flag.in Flag.out
   rem Check for the standard "End Of piped File" mark
   if "!line!" equ ":_EOF_:" exit /B
   rem Correctly manage CLS command
   if "!line:~0,1!" equ "!cls!" (
      cls
      set "line=!line:~1!"
   )
   rem Duplicate the line in Stdout and the Tee output file
   echo(!line!
   echo(!line!>> %1
goto TeeProcess


@end


// JScript section

var fso = new ActiveXObject("Scripting.FileSystemObject");
// Process all lines of Stdin
while ( ! WScript.Stdin.AtEndOfStream ) {
   // Read the next line from Stdin
   var line = WScript.Stdin.ReadLine();
   // Wait for "Data Read" acknowledgement
   while ( ! fso.FileExists("Flag.out") ) {
      WScript.Sleep(10);
   }
   // Send the line to Batch section
   WScript.Stdout.WriteLine(line);
   // Set "Data Available" signal
   fso.MoveFile("Flag.out", "Flag.in");
}
// Wait for last "Data Read" acknowledgement
while ( ! fso.FileExists("Flag.out") ) {
      WScript.Sleep(10);
}
// Send the standard "End Of piped File" mark
WScript.Stdout.WriteLine(":_EOF_:");
fso.MoveFile("Flag.out", "Flag.in");

answered May 20, 2013 at 3:07

Aacini's user avatar

AaciniAacini

63.7k12 gold badges70 silver badges105 bronze badges

2

I was also looking for the same solution, after a little try, I was successfully able to achieve that in Command Prompt. Here is my solution :

@Echo off
for /f "Delims=" %%a IN (xyz.bat) do (
%%a > _ && type _ && type _ >> log.txt
)
@Echo on

It even captures any PAUSE command as well.

answered Dec 2, 2014 at 19:50

Koder101's user avatar

Koder101Koder101

82416 silver badges28 bronze badges

Something like this should do what you need?

%DATE%_%TIME% > c:a.txt & type c:a.txt
ipconfig >> c:a.txt & type c:a.txt
ping localhost >> c:a.txt & type c:a.txt
pause

LarsTech's user avatar

LarsTech

80.1k14 gold badges150 silver badges222 bronze badges

answered Apr 5, 2016 at 13:40

Richard K's user avatar

Richard KRichard K

511 silver badge1 bronze badge

1

Here’s a sample of what I’ve used based on one of the other answers

@echo off
REM SOME CODE
set __ERROR_LOG=c:errors.txt
REM set __IPADDRESS=x.x.x.x

REM Test a variable
if not defined __IPADDRESS (
     REM Call function with some data and terminate
     call :TEE %DATE%,%TIME%,IP ADDRESS IS NOT DEFINED
     goto :EOF
)

REM If test happens to be successful, TEE out a message and end script.
call :TEE Script Ended Successful
goto :EOF


REM THE TEE FUNCTION
:TEE
for /f "tokens=*" %%Z in ("%*") do (
     >  CON ECHO.%%Z
     >> "%__ERROR_LOG%" ECHO.%%Z
     goto :EOF
)

answered Nov 2, 2011 at 18:17

Ed Radke's user avatar

send output to console, append to console log, delete output from current command

dir  >> usb-create.1 && type usb-create.1 >> usb-create.log | type usb-create.1 && del usb-create.1

Andreas's user avatar

Andreas

5,2728 gold badges44 silver badges52 bronze badges

answered Jan 23, 2015 at 18:46

Dennis's user avatar

DennisDennis

1043 bronze badges

1

This is a variation on a previous answer by MTS, however it adds some functionality that might be useful to others. Here is the method that I used:

  • A command is set as a variable, that can be used later throughout the code, to output to the command window and append to a log file, using set _Temp_Msg_Cmd=
    • the command has escaped redirection using the carrot ^ character so that the commands are not evaluated initially
  • A temporary file is created with a filename similar to the batch file being run called %~n0_temp.txt that uses command line parameter extension syntax %~n0 to get the name of the batch file.
  • The output is appended to a separate log file %~n0_log.txt

Here is the sequence of commands:

  1. The output and error messages are sent to the temporary file ^> %~n0_temp.txt 2^>^&1
  2. The content of the temporary file is then both:
    • appended to the logfile ^& type %~n0_temp.txt ^>^> %~n0_log.txt
    • output to the command window ^& type %~n0_temp.txt
  3. The temporary file with the message is deleted ^& del /Q /F %~n0_temp.txt

Here is the example:

set _Temp_Msg_Cmd= ^> %~n0_temp.txt 2^>^&1 ^& type %~n0_temp.txt ^>^> %~n0_log.txt ^& type %~n0_temp.txt ^& del /Q /F %~n0_temp.txt

This way then the command can simply be appended after later commands in a batch file that looks a lot cleaner:

echo test message %_Temp_Msg_Cmd%

This can be added to the end of other commands as well. As far as I can tell it will work when messages have multiple lines. For example the following command outputs two lines if there is an error message:

net use M: /D /Y %_Temp_Msg_Cmd%

Community's user avatar

answered Jul 27, 2015 at 16:36

ClearBlueSky85's user avatar

Just like unix.

dir | tee a.txt

Does work On windows XP, it requires mksnt installed.

It displays on the prompt as well as appends to the file.

Corey's user avatar

Corey

1,1573 gold badges21 silver badges37 bronze badges

answered May 3, 2013 at 12:47

user2346926's user avatar

This is not another answer, but more an overview and clarification to the already existed answers like
Displaying Windows command prompt output and redirecting it to a file
and others

I’ve found for myself that there is a set of issues what makes a set of tee implementations are not reliable in the Windows (Windows 7 in mine case).

I need to use specifically a tee implementation because have already uses a batch script with self redirection:

@echo off

setlocal


... some conditions here ..

rem the redirection
"%COMSPEC%" /C call %0 %* 2>&1 | "<path_to_tee_utililty>" ".log<log_file_name_with_date_and_time>.%~nx0.log"
exit /b

:IMPL
... here the rest of script ...

The script and calls to some utilities inside the script can break the output if used together with a tee utility.


  1. The gnuwin32 implementation:

http://gnuwin32.sourceforge.net/packages/coreutils.htm

Pros:

  • Correctly handles standard output together with a console progress bar, where the r character is heavily used.

Cons:

  • Makes console progress bars to draw only in a log file, but it has not duplicated or visible in the console window.
  • Throws multiple error messages Cwrite error: No such file or directory because seems the cmd interpreter closes the pipe/stdout too early and can not self close after that (spamming until termination).
  • Does not duplicate/print the output from the pause command (Press any key to continue...) in the console window.

  1. The wintee implementation:

https://code.google.com/archive/p/wintee/

https://github.com/rbuhl/wintee

Pros:

  • Shows a console progress bar both in the console window and in a log file (multiple prints).
  • Does duplicate/print the output from the pause command (Press any key to continue...) in the console window.

Cons:

  • Incorrectly handles the r character, output is mixed and messed (https://code.google.com/archive/p/wintee/issues/7 ).
  • Having other issues: https://code.google.com/archive/p/wintee/issues

  1. The UnxUtils implementation:

http://unxutils.sourceforge.net/

https://sourceforge.net/projects/unxutils/files/unxutils/current/

Pros

  • Shows a console progress bar both in the console window and in a log file (multiple prints).
  • Correctly handles the r character.
  • Does duplicate/print the output from the pause command (Press any key to continue...) in the console window.

Cons

Not yet found


  1. The ss64.net implementation:

http://ss64.net/westlake/nt

http://ss64.net/westlake/nt/tee.zip

Pros:

  • Shows a console progress bar both in the console window and in a log file (multiple prints).

Cons:

  • Incorrectly handles the r character, output is mixed and messed
  • For some reason does duplicate/print the output from the pause command (Press any key to continue...) in the console window AFTER a key press.

  1. The ritchielawrence mtee implementation:

https://ritchielawrence.github.io/mtee

https://github.com/ritchielawrence/mtee

Pros

  • Shows a console progress bar both in the console window and in a log file (multiple prints).
  • Correctly handles the r character.
  • Does duplicate/print the output from the pause command (Press any key to continue...) in the console window.
  • The error code retain feature w/o a need to use workaround with the doskey (/E flag, Windows command interpreter: how to obtain exit code of first piped command )

Cons

  • Does not support forward slash characters in the path to a log file (https://github.com/ritchielawrence/mtee/issues/6 )

  • Has a race condition issue, when can not extract a pipe process exit code because it has closed before it’s access (https://github.com/ritchielawrence/mtee/issues/4 )


So, if you are choosing the tee utility implementation between the above, then a better choice is the UnxUtils or mtee.


If you are searching for a better implementation with more features and less issues, then you can use callf utility:
https://github.com/andry81/contools/blob/trunk/Utilities/src/callf/help.tpl

You can run instead of:

call test.bat | mtee /E 1.log

This:

callf.exe /ret-child-exit /tee-stdout 1.log /tee-stdout-dup 1 "" "cmd.exe /c call test.bat"

It is better because it can pipe stdout separately from stderr and you can even pipe between processes with Administrator privileges isolation using named pipes.

answered Jul 7, 2020 at 9:09

Andry's user avatar

AndryAndry

2,02228 silver badges27 bronze badges

2

@echo on

set startDate=%date%
set startTime=%time%

set /a sth=%startTime:~0,2%
set /a stm=1%startTime:~3,2% - 100
set /a sts=1%startTime:~6,2% - 100


fullprocess.bat > C:LOGS%startDate%_%sth%.%stm%.%sts%.LOG | fullprocess.bat

This will create a log file with the current datetime and you can the console lines during the process

Vladimir's user avatar

Vladimir

170k36 gold badges384 silver badges312 bronze badges

answered Dec 3, 2010 at 14:15

7thSphere's user avatar

1

I use a batch subroutine with a «for» statement to get the command output one line at a time and both write that line to a file and output it to the console.

@echo off
set logfile=test.log

call :ExecuteAndTee dir C:Program Files

Exit /B 0

:ExecuteAndTee
setlocal enabledelayedexpansion
echo Executing '%*'
  for /f "delims=" %%a in ('%* 2^>^&1') do (echo.%%a & echo.%%a>>%logfile%)
endlocal
Exit /B 0

answered Feb 27, 2014 at 21:45

Cody Barnes's user avatar

Cody BarnesCody Barnes

3583 silver badges8 bronze badges

1

If you’re on the CLI, why not use a FOR loop to «DO» whatever you want:

for /F "delims=" %a in ('dir') do @echo %a && echo %a >> output.txt

Great resource on Windows CMD for loops: https://ss64.com/nt/for_cmd.html
The key here is setting the delimeters (delims), that would break up each line of output, to nothing. This way it won’t break on the default of white-space. The %a is an arbitrary letter, but it is used in the «do» section to, well… do something with the characters that were parsed at each line. In this case we can use the ampersands (&&) to execute the 2nd echo command to create-or-append (>>) to a file of our choosing. Safer to keep this order of DO commands in case there’s an issue writing the file, we’ll at least get the echo to the console first. The at sign (@) in front of the first echo suppresses the console from showing the echo-command itself, and instead just displays the result of the command which is to display the characters in %a. Otherwise you’d see:

echo Volume in drive [x] is Windows
Volume in drive [x] is Windows

UPDATE: /F skips blank lines and only fix is to pre-filter the output adding a character to every line (maybe with line-numbers via the command find). Solving this in CLI isn’t quick or pretty. Also, I didn’t include STDERR, so here’s capturing errors as well:

for /F "delims=" %a in ('dir 2^>^&1') do @echo %a & echo %a >> output.txt

Redirecting Error Messages

The carets (^) are there to escape the symbols after them, because the command is a string that’s being interpreted, as opposed to say, entering it directly on the command-line.

answered Feb 6, 2019 at 20:37

Had To Ask's user avatar

I just found a way to use the perl as alternative, e.g.:

CMD1 | perl -ne "print $_; print STDERR $_;" 2> OUTPUT.TEE

answered Jul 2, 2020 at 11:05

pegasus's user avatar

Following helps if you want something really seen on the screen — even if the batch file was redirected to a file. The device CON maybe used also if redirected to a file

Example:

ECHO first line on normal stdout. maybe redirected
ECHO second line on normal stdout again. maybe redirected
ECHO third line is to ask the user. not redirected  >CON
ECHO fourth line on normal stdout again. maybe redirected

Also see good redirection description: http://www.p-dd.com/chapter7-page14.html

answered Jul 8, 2009 at 8:52

Baresi der LiberoBaresi der Libero

How do I display and redirect output
to a file. Suppose if I use dos
command, dir > test.txt ,this command
will redirect output to file test.txt
without displaying the results. how to
write a command to display the output
and redirect output to a file using
DOS i.e., windows command prompt, not
in UNIX/LINUX.

You may find these commands in biterscripting ( http://www.biterscripting.com ) useful.

var str output
lf > $output
echo $output                            # Will show output on screen.
echo $output > "test.txt"               # Will write output to file test.txt.
system start "test.txt"                 # Will open file test.txt for viewing/editing.

answered Jan 10, 2010 at 21:35

P M's user avatar

This works in real time but is also kind a ugly and the performance is slow. Not well tested either:

@echo off
cls
SET MYCOMMAND=dir /B
ECHO File called 'test.bat' > out.txt
for /f "usebackq delims=" %%I in (`%MYCOMMAND%`) do (
  ECHO %%I
  ECHO %%I >> out.txt
) 
pause

answered Sep 20, 2012 at 17:48

djangofan's user avatar

djangofandjangofan

27.6k57 gold badges188 silver badges282 bronze badges

1

An alternative is to tee stdout to stderr within your program:

in java:

System.setOut(new PrintStream(new TeeOutputStream(System.out, System.err)));

Then, in your dos batchfile: java program > log.txt

The stdout will go to the logfile and the stderr (same data) will show on the console.

answered Nov 23, 2012 at 19:50

The Coordinator's user avatar

The CoordinatorThe Coordinator

12.8k11 gold badges43 silver badges73 bronze badges

I install perl on most of my machines so an answer using perl: tee.pl

my $file = shift || "tee.dat";
open $output, ">", $file or die "unable to open $file as output: $!";
while(<STDIN>)
{
    print $_;
    print $output $_;
}
close $output;

dir | perl tee.pl
or
dir | perl tee.pl dir.bat

crude and untested.

answered Feb 19, 2014 at 15:39

DannyK's user avatar

DannyKDannyK

1,33216 silver badges23 bronze badges

Rob van der Woude's Scripting Pages

Display & Redirect Output

On this page I’ll try to explain how redirection works.
To illustrate my story there are some examples you can try for yourself.

For an overview of redirection and piping, view my original redirection page.

Display text

To display a text on screen we have the ECHO command:

ECHO Hello world

This will show the following text on screen:

Hello world

When I say «on screen», I’m actually referring to the «DOS Prompt», «console» or «command window», or whatever other «alias» is used.

Streams

The output we see in this window may all look alike, but it can actually be the result of 3 different «streams» of text, 3 «processes» that each send their text to thee same window.

Those of you familiar with one of the Unix/Linux shells probably know what these streams are:

  • Standard Output
  • Standard Error
  • Console

Standard Output is the stream where all, well, standard output of commands is being sent to.
The ECHO command sends all its output to Standard Output.

Standard Error is the stream where many (but not all) commands send their error messages.

And some, not many, commands send their output to the screen bypassing Standard Output and Standard Error, they use the Console.
By definition Console isn’t a stream.

There is another stream, Standard Input: many commands accept input at their Standard Input instead of directly from the keyboard.
Probably the most familiar example is MORE:

DIR /S | MORE

where the MORE command accepts DIR‘s Standard Output at its own Standard Input, chops the stream in blocks of 25 lines (or whatever screen size you may use) and sends it to its own Standard Output.

(Since MORE‘s Standard Input is used by DIR, MORE must catch its keyboard presses (the «Any Key») directly from the keyboard buffer instead of from Standard Input.)

Redirection

You may be familiar with «redirection to NUL» to hide command output:

ECHO Hello world>NUL

will show nothing on screen.
That’s because >NUL redirects all Standard Output to the NUL device, which does nothing but discard it.

Now try this (note the typo):

EHCO Hello world>NUL

The result may differ for different operating system versions, but in Windows XP I get the following error message:

'EHCO' is not recognized as an internal or external command, operable program or batch file.

This is a fine demonstration of only Standard Output being redirected to the NUL device, but Standard Error still being displayed.

Redirecting Standard Error in «true» MS-DOS (COMMAND.COM) isn’t possible (actually it is, by using the CTTY command, but that would redirect all output including Console, and input, including keyboard).
In Windows NT 4 and later (CMD.EXE) and in OS/2 (also CMD.EXE) Standard Error can be redirected by using 2> instead of >

A short demonstration. Try this command:

ECHO Hello world 2>NUL

What you should get is:

Hello world

You see? The same result you got with ECHO Hello world without the redirection.
That’s because we redirected the Standard Error stream to the NUL device, but the ECHO command sent its output to the Standard Output stream, which was not redirected.

Now make a typo again:

EHCO Hello world 2>NUL

What did you get?
Nothing
That’s because the error message was sent to the Standard Error stream, which was in turn redirected to the NUL device by 2>NUL

When we use > to redirect Standard Output, CMD.EXE interprets this as 1>, as can be seen by writing and running this one-line batch file «test.bat»:

DIR > NUL

Now run test.bat in CMD.EXE and watch the result:

C:>test.bat

C:>DIR  1>NUL

C:>_

It looks like CMD.EXE uses 1 for Standard Output and 2 for Standard Error.
We’ll see how we can use this later.

Ok, now that we get the idea of this concept of «streams», let’s play with it.
Copy the following code into Notepad and save it as «test.bat»:

@ECHO OFF
ECHO This text goes to Standard Output
ECHO This text goes to Standard Error 1>&2
ECHO This text goes to the Console>CON

Run test.bat in CMD.EXE, and this is what you’ll get:

C:>test.bat
This text goes to Standard Output
This text goes to Standard Error
This text goes to the Console

C:>_

Now let’s see if we can separate the streams again.
Run:

test.bat > NUL

and you should see:

C:>test.bat
This text goes to Standard Error
This text goes to the Console

C:>_

We redirected Standard Output to the NUL device, and what was left were Standard Error and Console.

Next, run:

test.bat 2> NUL

and you should see:

C:>test.bat
This text goes to Standard Output
This text goes to the Console

C:>_

We redirected Standard Error to the NUL device, and what was left were Standard Output and Console.

Nothing new so far. But the next one is new:

test.bat > NUL 2>&1

and you should see:

C:>test.bat
This text goes to the Console

C:>_

This time we redirected both Standard Output and Standard Error to the NUL device, and what was left was only Console.
It is said Console cannot be redirected, and I believe that’s true.
I can assure you I did try!

To get rid of screen output sent directly to the Console, either run the program in a separate window (using the START command), or clear the screen immediately afterwards (CLS).

In this case, we could also have used test.bat >NUL 2>NUL
This redirects Standard Output to the NUL device and Standard Error to the same NUL device.
With the NUL device that’s no problem, but when redirecting to a file one of the redirections will lock the file for the other redirection.
What 2>&1 does, is merge Standard Error into the Standard Output stream, so Standard output and Standard Error will continue as a single stream.

Redirect «all» output to a single file:

Run:

test.bat > test.txt 2>&1

and you’ll get this text on screen (we’ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

This text goes to the Console

You should also get a file named test.txt with the following content:

This text goes to Standard Output
This text goes to Standard Error
Note: The commands
test.bat  > test.txt 2>&1
test.bat 1> test.txt 2>&1
test.bat 2> test.txt 1>&2
all give identical results.

Redirect errors to a separate error log file:

Run:

test.bat > testlog.txt 2> testerrors.txt

and you’ll get this text on screen (we’ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

This text goes to the Console

You should also get a file named testlog.txt with the following content:

This text goes to Standard Output

and another file named testerrors.txt with the following content:

This text goes to Standard Error

Nothing is impossible, not even redirecting the Console output.

Unfortunately, it can be done only in the old MS-DOS versions that came with a CTTY command.

The general idea was this:

CTTY NUL
ECHO Echo whatever you want, it won't be displayed on screen no matter what.
ECHO By the way, did I warn you that the keyboard doesn't work either?
ECHO I suppose that's why CTTY is no longer available on Windows systems.
ECHO The only way to get control over the computer again is a cold reboot,
ECHO or the following command:
CTTY CON

A pause or prompt for input before the CTTY CON command meant one had to press the reset button!

Besides being used for redirection to the NUL device, with CTTY COM1 the control could be passed on to a terminal on serial port COM1.

Escaping Redirection (not to be interpreted as «Avoiding Redirection»)

Redirection always uses the main or first command’s streams:

START command > logfile

will redirect START‘s Standard Output to logfile, not command‘s!
The result will be an empty logfile.

A workaround that may look a bit intimidating is grouping the command line and escaping the redirection:

START CMD.EXE /C ^(command ^> logfile^)

What this does is turn the part between parentheses into a «literal» (uninterpreted) string that is passed to the command interpreter of the newly started process, which then in turn does interpret it.
So the interpretation of the parenthesis and redirection is delayed, or deferred.

Note: Be careful when using workarounds like these, they may be broken in future (or even past) Windows versions.

A safer way to redirect STARTed commands’ output would be to create and run a «wrapper» batch file that handles the redirection.
The batch file would look like this:

command > logfile

and the command line would be:

START batchfile

Some «best practices» when using redirection in batch files:

  • Use >filename.txt 2>&1 to merge Standard Output and Standard Error and redirect them together to a single file.
    Make sure you place the redirection «commands» in this order.
  • Use >logfile.txt 2>errorlog.txt to redirect success and error messages to separate log files.
  • Use >CON to send text to the screen, no matter what, even if the batch file’s output is redirected.
    This could be useful when prompting for input even if the batch file’s output is being redirected to a file.
  • Use 1>&2 to send text to Standard Error.
    This can be useful for error messages.
  • It’s ok to use spaces in redirection commands.
    Note however, that a space between an ECHO command and a > will be redirected too.
    DIR>filename.txt and DIR > filename.txt are identical, ECHO Hello world>filename.txt and ECHO Hello world > filename.txt are not, even though they are both valid.
    It is not ok to use spaces in >> or 2> or 2>&1 or 1>&2 (before or after is ok).
  • In Windows NT 4, early Windows 2000 versions, and OS/2 there used to be some ambiguity with ECHOed lines ending with a 1 or 2, immediately followed by a >:
    ECHO Hello world2>file.txt would result in an empty file file.txt and the text Hello world (without the trailing «2») on screen (CMD.EXE would interpret it as ECHO Hello world 2>file.txt).
    In Windows XP the result is no text on screen and file.txt containing the line Hello world2, including the trailing «2» (CMD.EXE interprets it as ECHO Hello world2 >file.txt).
    To prevent this ambiguity, either use parentheses or insert an extra space yourself:
    ECHO Hello World2 >file.txt
    (ECHO Hello World2)>file.txt
  • «Merging» Standard Output and Standard Error with 2>&1 can also be used to pipe a command’s output to another command’s Standard Input:
    somecommand 2>&1 | someothercommand
  • Redirection overview page
  • Use the TEE command to display on screen and simultaneously redirect to file

page last modified: 2016-09-19

You haven’t shown the command you are using that is failing. If you show it in your question, it might be easier to find a solution for you.

I expect your command is something like this:

C:>foo.exe|c:Program Files (x86)somethingtest.txt

The error you are receiving is somewhat of a clue:

'c:/Program' is not recognized as an internal or external command, operable program or batch file.

First:
... is not recognized as an internal or external command, operable program or batch file.

This typically happens when you try to redirect to a file using a | instead of a >.

Second:
'c:/Program' ...

When specifying a filename (or path) that contains spaces, you must surround it in double-quote marks ("...") . This is because when the OS is determining the file to redirect to, it will stop looking for the filename when it encounters an unquoted space: "c:/Program".

Try this:

foo.exe>"c:Program Files (x86)somethingtest.txt"

If the above doesn’t work to capture the output from foo.exe to the text file, then there is another possibility…

If the program foo.exe is writing its output to STDERR instead of STDOUT, the output of foo.exe will not be captured by using simple redirection with a single >. You would have to do it like this:

foo.exe>"c:Program Files (x86)somethingtest.txt" 2>&1

Edit:

Here is an explanation of file redirection and the 2>&1 notation.

When a program writes to the terminal, it can write to one of two Streams.

  1. Stream 1 is referred to as STDOUT or Standard-Output. Typically, programs write their «Normal» output to stream 1.

  2. Stream 2 is referred to as STDERR or Standard-Error. Typically, programs write their «Error» output (error and warning messages) to stream 2.

Whether a program writes a particular output to STDOUT or STDERR is determined by the programmer and how they wrote the program. Some programs are written to send all output (normal output and errors) to STDOUT.

When a program is run with no output redirection, all normal and error output is sent to the terminal screen without any distinction between what is STDOUT output or STDERR output.

When you do «normal» redirection with a single > like this:

foo.exe > "c:Program Files (x86)somethingtest.txt"

you are not specifying which Stream is being redirected to the file, so Stream 1 is assumed.

It’s the same as if you typed it like this:

foo.exe 1> "c:Program Files (x86)somethingtest.txt"

This tells the command interpreter (cmd.exe) to capture the program output for STDOUT (Stream 1) to the specified filename. The 1 in 1> refers to Stream 1.

In this case all the normal program is captured to the file, but if the program writes to STDERR (Stream 2), that output will not be captured and will be shown on the screen. This is generally the «desired» way to do it so that while you are capturing the normal program output, you can see on the screen if an error occurs.

If you want to capture «Normal» output to one file, and «Error» output to a different file you can do it like this:

    foo.exe > "c:output.txt" 2> "C:error.txt"
or
    foo.exe 1> "c:output.txt" 2> "C:error.txt"

If you want the «Normal» output and the «Error» output to be captured to the same file, you can specify it like this:

foo.exe > "c:output.txt" 2>&1

This is basically a «shorthand» way of specifying it and it means to redirect Stream 1 to the specified file, and to also redirect Stream 2 to the same «place» (file) as Stream 1.


Edit:

Pacerier asked:

Is there any difference between foo.exe > «c:output.txt» 2>&1 and foo.exe > «c:output.txt» 2>»c:output.txt»? Are they identical?

Short answer: You would think they are identical, but no. They are different.

With redirection using >"filename.ext", 1>"filename.ext", or 2>"filename.ext", the > causes the output to be written to a new file named «filename.ext». If the file «filename.ext» already exists, it will be deleted first.

So, using:

foo.exe > «c:output.txt» 2>»c:output.txt»

causes a «conflict» where both redirections are trying to write to the same file and both are trying to delete the file if it already exists. This will likely cause undesired behavior. Generally, one or the other, or both, of the outputs will NOT be captured fully, or predictably.

The actual result will depend on the operating system and version, and may also depend on the command being executed. What will likely happen is:

1 The output sent to one of the redirections will be captured or partially captured, and the output sent to other redirection will be lost.
2 The operating system will complain about the command and neither of the outputs will be captured (fully).
3 Undefined, undesired, unpredictable, unexpected behavior.

On Windows 7 and likely on Windows Vista/8/10, and possibly on Windows XP, the operating system will complain about command and the command will be canceled.

For example (Windows 7): I have a folder named: "C:Tempemptyfolder" and a file named «nonexistantfile» doesn’t exist there.

C:>cd "Tempemptyfolder"

C:Tempemptyfolder>dir nonexistantfile>output.txt
File Not Found

C:Tempemptyfolder>type output.txt
 Volume in drive F is FFFFx1tb
 Volume Serial Number is 4011-A5C6

 Directory of C:Tempemptyfolder

C:Tempemptyfolder>

In this case, using one redirection (>output.txt), the output of the dir command is captured the the file: output.txt, and the error message File Not Found is shown on the screen… this is the expected behavior.

Now, using both redirections («>file» AND «2>file»):

C:Tempemptyfolder>dir nonexistantfile>output.txt 2>output.txt
The process cannot access the file because it is being used by another process.
C:Tempemptyfolder>type output.txt

C:Tempemptyfolder>

In this case, the operating system complained that the (outout) file is already in use. And the file «output.txt» ends up empty (0 bytes), and the output for both of the redirections was lost.

Now, lastly, using both redirections («>file» AND «2>&1»):

C:Tempemptyfolder>dir nonexistantfile>output.txt 2>&1

C:Tempemptyfolder>type output.txt
 Volume in drive C is CCCCCCCC
 Volume Serial Number is 1234-ABCD

 Directory of C:Tempemptyfolder

File Not Found

C:Tempemptyfolder>

In this case, «>file» causes the output for «stream 1» («standard output») to be captured to the file. And «2>&1» causes the output for «stream 2» («error output») to be sent through the already redirected «stream 1», and to also be captured to the (same) file.

It is also worth noting that the order is important. Reversing the order like this:

dir nonexistant 2>&1 >output.txt

is not the same and will probably not give you the desired result.

In this case, «2>&1», which is seen and precessed first, causes the output for «stream 2» («error output») to be redirected to the place where «stream 1» is currently directed to, which at that moment, is (by default), the screen. And «>file» causes the output for «stream 1» («standard output») to be captured to the file. The end result, is that the output of the command («stream 1») will be captured to the file, but the error output («stream 2»), will still go to the screen (not to the file).

Many times we need to run commands for various purposes from windows command prompt. The output of the command depends on command type. If the output is very large then we need to scroll the window to find out the desired information which is very annoying. There are some commands that provide important information and sometimes we need to share this information with our technical stuffs or use on other documents. Taking the screenshot of the output is not a good choice and for the large output all outputs can’t be taken as single screenshot image. Another problem of screenshot is that if we want to copy some text from the command output for other use then it is not possible to do from image. So if the command output can be saved as a text file then it will be very helpful for the user to access content easily. How you can save or redirect the command prompt output to a text file on windows operating system is shown in this article.

To save any command output from the command prompt, you have to use the redirect operator (single angle bracket) “>” and the command using the following syntax:

Command > Filename

Suppose we want to find out the directory list of any drive of your computer and save the output into a text file name directorylist.txt on D: drive. If the file does not exist then the new file will be created and if the file exists then the command output will overwrite the file content. Type the ‘dir’ command in the following way to save the output on output.txt file.

dir > d:output.txt

Now open D: drive and search the file output.txt. If the file exists then double click on the file to open it.

If we the check the content of the file then it will be found that both command prompt output and file content are same.

If we want to run multiple commands in the command prompt and save it in a file then last command output will be overwritten every time. If we run dir and ping commands one after another then the text file contains only the last output.

dir > d:output.txt

ping google.com > d:output.txt

To solve this problem, we need to append the command outputs in the redirecting file. We have to use double angle bracket “>>” to append the output.

ping hotmail.com > d:output2.txt

ping yahoo.com >> d:output2.txt

Now if we open the output2.txt file then it will show both two command outputs.

When we want to save the redirected file in a particular drive and the error arrives or file not creates. This means you have no permission to write on this drive. This error occurs for that drive where Windows is installed. By default, we install Windows in “C:” drive. So when we want to create any file in drive C: we will get the access permission error.

ipconfig>c:ipconfig.txt

We have to open the command prompt window with administrator permission to solve this problem. Right click on the cmd option and select “Run as Administrator” from the pop up menu.

Now if we redirect the output of the commands into the text file then the file will be created.

Conclusion

In this way, we can save any number of command outputs to a text file for accessing information easily or sharing the information with others when requires.

What to Know

  • The > redirection operator goes between the command and the file name, like ipconfig > output.txt.
  • If the file already exists, it’ll be overwritten. If it doesn’t, it will be created.
  • The >> operator appends the file. Instead of overwriting the file, it appends the command output to the end of it.

Use a redirection operator to redirect the output of a command to a file. All the information displayed in Command Prompt after running a command can be saved to a file, which you can reference later or manipulate however you like.

How to Use Redirection Operators

While there are several redirection operators, two, in particular, are used to output the results of a command to a file: the greater-than sign (>) and the double greater-than sign (>>).

The easiest way to learn how to use these redirection operators is to see some examples:

ipconfig /all > networksettings.txt

In this example, all the information normally seen on screen after running ipconfig /all, is saved to a file by the name of networksettings.txt. It’s stored in the folder to the left of the command, the root of the D: drive in this case.

The > redirection operator goes between the command and the filename. If the file already exists, it’ll be overwritten. If it doesn’t already exist, it will be created.

Although a file will be created if doesn’t already exist, folders will not. To save the command output to a file in a specific folder that doesn’t yet exist, first, create the folder and then run the command. Make folders without leaving Command Prompt with the mkdir command.

ping 192.168.86.1 > "C:UsersjonfiDesktopPing Results.txt"

Here, when the ping command is executed, Command Prompt outputs the results to a file by the name of Ping Results.txt located on the jonfi user’s desktop, at C:UsersjonfiDesktop. The entire file path in wrapped in quotes because a space involved.

Remember, when using the > redirection operator, the file specified is created if it doesn’t already exist and is overwritten if it does exist.

The Append Redirection Operator

The double-arrow operator appends, rather than replaces, a file:

ipconfig /all >> \serverfilesofficenetsettings.log

This example uses the >> redirection operator which functions in much the same way as the > operator, only instead of overwriting the output file if it exists, it appends the command output to the end of the file.

Here’s an example of what this LOG file might look like after a command has been exported to it:

The >> redirection operator is useful when you’re collecting similar information from different computers or commands, and you’d like all that data in a single file.

The above redirection operator examples are within the context of Command Prompt, but you can also use them in a BAT file. When you use a BAT file to pipe a command’s output to a text file, the exact same commands described above are used, but instead of pressing Enter to run them, you just have to open the .BAT file.

Use Redirection Operators in Batch Files

Redirection operators work in batch files by including the command just as you would from the Command Prompt:

tracert yahoo.com > C:yahootracert.txt

The above is an example of how to make a batch file that uses a redirection operator with the tracert command.

The yahootracert.txt file (shown above) will be created on the C: drive several seconds after executing the sample.bat file. Like the other examples above, the file shows everything Command Prompt would have revealed if the redirection operator wasn’t used.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

The ‘>’ operator is used to redirect the output to a new file, the ‘>>’ is used to redirect the output and append to the file.
Now both the STDOUT and STDERR are written to the console by default. Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the “>” symbol, you are only redirecting STDOUT. In order to redirect STDERR you have to specify “2>” for the redirection symbol. This selects the second output stream which is STDERR.

For Example, running the dir command on a file gives both stdout and stderr like below:

1
2
3
4
5
6
7
C: dir nosuchfile.txt
 Volume in drive C has no label.
 Volume Serial Number is B8A1-5FD1
 
 Directory of C:
 
File Not Found

Here the “File Not Found” message is the STDERR and the rest was for STDOUT. Now if you want to redirect the whole output to a file, just running the command dir nosuchfile.txt > result.log will not cut it. You need to do one of the following:

Sending the STDERR and STDOUT to different files:

1
dir nosuchfile.txt > out.log 2>error.log

Sending the STDERR and STDOUT to Same file:

1
dir nosuchfile.txt > alloutput.log 2>&1

Here the 2>&1 instructs that the STDERR to be redirected to STDOUT which is in-turn writing out to alloutput.log file.

“Know thy commands.”
-Rushi

Перенаправление ввода-вывода в cmd

Перенаправление стандартных ввода-вывода и ошибок

С помощью переназначения устройств ввода/вывода одна программа может направить свой вывод на вход другой или перехватить вывод другой программы, используя его в качестве своих входных данных. Таким образом, имеется возможность передавать информацию от процесса к процессу при минимальных программных издержках. Практически это означает, что для программ, которые используют стандартные входные и выходные устройства, операционная система позволяет:

  • выводить сообщения программ не на экран (стандартный выходной поток), а в файл или на принтер (перенаправление вывода);
  • читать входные данные не с клавиатуры (стандартный входной поток), а из заранее подготовленного файла (перенаправление ввода);
  • передавать сообщения, выводимые одной программой, в качестве входных данных для другой программы (конвейеризация или композиция команд).

Из командной строки эти возможности реализуются следующим образом. Для того, чтобы перенаправить текстовые сообщения, выводимые какой-либо командой из командной строки, в текстовый файл, нужно использовать конструкцию команда > имя_файла. Если при этом заданный для вывода файл уже существовал, то он перезаписывается (старое содержимое теряется), если не существовал создается. Можно также не создавать файл заново, а дописывать информацию, выводимую командой, в конец существующего файла. Для этого команда перенаправления вывода должна быть задана так: команда >> имя_файла. С помощью символа < можно прочитать входные данные для заданной команды не с клавиатуры, а из определенного (заранее подготовленного) файла: команда < имя_файла

Примеры перенаправления ввода/вывода в командной строке

Приведем несколько примеров перенаправления ввода/вывода.

1. Вывод результатов команды ping в файл  ping ya.ru > ping.txt

2. Добавление текста справки для команды XCOPY в файл copy.txt: XCOPY /? >> copy.txt

В случае необходимости сообщения об ошибках (стандартный поток ошибок) можно перенаправить в текстовый файл с помощью конструкции команда 2> имя_файла В этом случае стандартный вывод будет производиться на экран. Также имеется возможность информационные сообщения и сообщения об ошибках выводить в один и тот же файл. Делается это следующим образом: команда > имя_файла 2>&1

Например, в приведенной ниже команде стандартный выходной поток и стандартный поток ошибок перенаправляются в файл copy.txt: XCOPY A:1.txt C: > copy.txt 2>&1

Windows Command-line tools are great for troubleshooting, as well as automation. But, if you’re stumped when a tech support guy on the phone asks you to run a built-in console command and copy the output displayed for diagnosing a problem, these Command Prompt basics will come in handy.

This post explains how to copy or redirect Command Prompt output to a file or the clipboard.

Table of Contents

  • Open a Command Prompt window
  • Copy Command Prompt output to Clipboard
    • Using keyboard shortcuts
    • Using the Edit menu
    • Piping the output to Clip (Clip.exe tool)
  • Redirect Command-line output to a file
    • Redirecting the output to a new file
    • Redirecting the output to a file (append contents)
  • Take a Screenshot

Opening a Command Prompt window

To open a Command Prompt window, press WinKey + R to launch the Run dialog. Type in cmd.exe and press Ok. In Windows 8.1 and Windows 10, you can right-click Start and click Command Prompt. There are several other ways to open Command Prompt.

Command Prompt window

If the console tool you’re running or the operation you’re performing requires administrative privileges, you need to open Command Prompt as administrator (also known as “elevated” Command Prompt.)

In the Command Prompt window, type in the command you want to run. For example, someone who’s helping you wants to know your system information by running SystemInfo command, type systeminfo and press ENTER.

copy command prompt output

Copying the output to clipboard

To copy the command prompt output to the clipboard, use one of the methods.

Using Keyboard: Press Ctrl + A to select all text, and press ENTER to copy it to the clipboard.

Using the Edit menu: Right-click the Command Prompt title bar → EditSelect All. Repeat the same, and this time, select Copy from the Edit menu.

copy command prompt output

Using Clip.exe console tool: The Clip.exe console tool is built-in to Windows, starting with Windows Vista and up to Windows 10. This tool copies the data redirected or passed to it, into the clipboard. You can redirect the output of your console tool or command to the clipboard using the built-in Clip.exe tool by piping the output. The command you’d run is:

systeminfo |clip

That would copy the output of the systeminfo command to the Windows Clipboard. This is done by Clip.exe receiving the command-line output directly.

Once the output is sent to the clipboard, you can paste it into a text editor. For example, you can open Notepad and paste (Ctrl + V) the contents there.

copy command prompt output

Redirecting the output to a new file

You can redirect the command-line output to a file instead of Clipboard. This method can be useful if the output is too lengthy, containing several hundreds of lines that can easily exceed the Command Prompt window’s screen buffer size. To output the results to a file, use this syntax/examples:

systeminfo >%temp%systeminfo.txt

That would create a file named systeminfo.txt in the user’s Temp folder. To write the output to a file on your desktop, you’d use:

systeminfo >%userprofile%desktopsysteminfo.txt

Redirecting the output to a file by appending

The previous command would create a new file or erase the previous file (if one exists with the same name). If you want to append the command-line output to a file, use double greater-than symbols >>, as below:

ipconfig >>%userprofile%desktopsysteminfo.txt
systeminfo >>%userprofile%desktopsysteminfo.txt

That would output the contents of Ipconfig and Systeminfo commands to the same file. If a file exists with the same name systeminfo.txt, it would be used. Otherwise, a new file would be created.

Another example

ipconfig >%userprofile%desktopinfo.txt
sc query wuauserv >>%userprofile%desktopinfo.txt
dir d:tools*.exe >>%userprofile%desktopinfo.txt
dir C:WindowsSystem32Tasks /s /b >>%userprofile%desktopinfo.txt

Command Prompt window

The first command would create a new file (as a single > symbol is used) named info.txt. Subsequent commands would output the results to the existing info.txt file (double >> symbol).

Take a Screenshot

In some cases, you may not require the text output, and a screenshot is sufficient. Win + PrntScrn keystroke is used to take a screenshot quickly in Windows 8 and 10. Or use the excellent built-in Snipping Tool. Check out How to Take a Screenshot in Windows for a detailed guide.

I hope this guide helped you learn how to copy or redirect Command Prompt output to a file or the clipboard.


One small request: If you liked this post, please share this?

One «tiny» share from you would seriously help a lot with the growth of this blog.
Some great suggestions:

  • Pin it!
  • Share it to your favorite blog + Facebook, Reddit
  • Tweet it!

So thank you so much for your support. It won’t take more than 10 seconds of your time. The share buttons are right below. :)


Понравилась статья? Поделить с друзьями:
  • Windows bootable image creator как пользоваться
  • Windows can t verify the publisher of this driver software
  • Windows cmd delete folder with files
  • Windows boot manager это жесткий диск
  • Windows can t be installed on this drive