Windows cmd output to file

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.4k5 gold badges50 silver badges71 bronze badges

14

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

12

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,3161 gold badge39 silver badges58 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

30.1k48 gold badges152 silver badges225 bronze badges

answered Feb 2, 2011 at 5:25

Andy Welch's user avatar

Andy WelchAndy Welch

5674 silver badges2 bronze badges

1

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

71.4k58 gold badges252 silver badges329 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.

18.3k11 gold badges59 silver badges79 bronze badges

answered Apr 28, 2009 at 7:01

Richard's user avatar

RichardRichard

1,1696 silver badges8 bronze badges

9

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,8852 gold badges17 silver badges18 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

e.d.n.a

1911 silver badge6 bronze badges

answered Jun 18, 2016 at 11:07

アリスター's user avatar

アリスターアリスター

3422 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,3405 gold badges40 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,3983 gold badges23 silver badges33 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.8k17 gold badges89 silver badges101 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

65.3k12 gold badges72 silver badges108 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

84415 silver badges28 bronze badges

1

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.8k14 gold badges153 silver badges226 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,4439 gold badges44 silver badges53 bronze badges

answered Jan 23, 2015 at 18:46

Dennis's user avatar

DennisDennis

1043 bronze badges

1

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/tree/HEAD/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,28229 silver badges28 bronze badges

2

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,2393 gold badges22 silver badges40 bronze badges

answered May 3, 2013 at 12:47

user2346926's user avatar

@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 badges387 silver badges313 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

Had To AskHad To Ask

691 silver badge4 bronze badges

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

28.6k61 gold badges196 silver badges290 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

13k11 gold badges44 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,34216 silver badges23 bronze badges

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.4k5 gold badges50 silver badges71 bronze badges

14

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

12

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,3161 gold badge39 silver badges58 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

30.1k48 gold badges152 silver badges225 bronze badges

answered Feb 2, 2011 at 5:25

Andy Welch's user avatar

Andy WelchAndy Welch

5674 silver badges2 bronze badges

1

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

71.4k58 gold badges252 silver badges329 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.

18.3k11 gold badges59 silver badges79 bronze badges

answered Apr 28, 2009 at 7:01

Richard's user avatar

RichardRichard

1,1696 silver badges8 bronze badges

9

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,8852 gold badges17 silver badges18 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

e.d.n.a

1911 silver badge6 bronze badges

answered Jun 18, 2016 at 11:07

アリスター's user avatar

アリスターアリスター

3422 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,3405 gold badges40 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,3983 gold badges23 silver badges33 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.8k17 gold badges89 silver badges101 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

65.3k12 gold badges72 silver badges108 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

84415 silver badges28 bronze badges

1

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.8k14 gold badges153 silver badges226 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,4439 gold badges44 silver badges53 bronze badges

answered Jan 23, 2015 at 18:46

Dennis's user avatar

DennisDennis

1043 bronze badges

1

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/tree/HEAD/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,28229 silver badges28 bronze badges

2

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,2393 gold badges22 silver badges40 bronze badges

answered May 3, 2013 at 12:47

user2346926's user avatar

@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 badges387 silver badges313 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

Had To AskHad To Ask

691 silver badge4 bronze badges

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

28.6k61 gold badges196 silver badges290 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

13k11 gold badges44 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,34216 silver badges23 bronze badges

One of the most useful ways to log and troubleshoot the behavior of commands or batch jobs that you run on Windows is to redirect output to a file.

However, there are a few different ways you can redirect command line writes to a file. The option you choose depends on how you want to view your command output.

How Windows Command Prompt Output Works

When you type a command in the Windows console (command prompt), the output from that command goes to two separate streams.

  • STDOUT: Standard Out is where any standard responses from commands go. For example the standard response for the DIR command is a list of files inside a directory.
  • STDERR: Standard Error is where any error messages go if there’s a problem with the command. For example if there aren’t any files in the directory, the DIR command will output “File Not Found” to the Standard Error stream.

You can redirect output to a file in Windows for both of these output streams.

Redirect Standard Output Write to New File

There are two ways you can redirect standard output of a command to a file. The first is to send the command output write to a new file every time you run the command.

To do this, open the command prompt and type:

dir test.exe > myoutput.txt

The > character tells the console to output STDOUT to the file with the name you’ve provided.

When you run this command, you’ll notice that there isn’t any response in the command window except the error that the file doesn’t exist.

This is because the standard output for the command was redirected to a file called myoutput.txt. The file now exists in the same directory where you ran the command. The standard error output still displays as it normally does.

Note: Be careful to change the active directory for the command prompt before running the command. This way you’ll know where the output files are stored.

You can view the standard output that went to the file by typing “myoutput.txt” in the command window. This will open the text file in your default text file viewer. For most people, this is usually Notepad.exe.

The next time you run the same command, the previous output file will be deleted. A new output file will be recreated with the latest command’s output.

Redirect Standard Output Writes to the Same File

What if you don’t want to overwrite the same file? Another option is to use >> rather than > to redirect to an output file. In the case of this example, you would type:

dir test.exe >> myoutput.txt

You’ll see the same output (the error only).

But in this case, instead of overwriting the output file, this command appends the new output to the existing output file.

Every time you run a command and append the output to a file, it’ll write the new standard output to the end of the existing file.

Redirect Standard Error To a File

The same way you can redirect standard output writes to a file, you can also output the standard error stream to a file.

To do this, you’ll need to add 2> to the end of the command, followed by the output error file you want to create.

In this example, you’ll type the command: 

dir test.exe > myoutput.txt 2> output.err

This sends the standard output stream to myoutput.txt, and the standard error stream to output.err. The result is that no output stream at all gets displayed in the console window.

However, you can see the error messages by typing output.err. This will open the file in your default text file viewer.

As you can see, any error messages from the command are output to the error file. Just as with the standard output, you can use >> instead to append the error to errors from previously run commands.

Redirect All Output Writes to a Same File

All of the approaches above result in multiple files. One file is for the standard output stream and the other is for the standard error stream.

If you want to include both of these outputs to the same file, you can do that too. To do this, you just need to redirect all output to the same file using the following command.

dir test.exe 1> myoutput.txt 2>&1

Here’s how this command works:

  • The standard output is directed to the output file identified by output number 1.
  • The standard error output identified by the number 2 is redirected to the output file identified by number 1.

This will append the error output to the end of the standard output.

This is a useful way to see all output for any command in one file. 

Silencing Standard or Error Output Streams

You can also turn off either Standard Output or Standard Error by redirecting the output to a NUL instead of a file.

Using the example above, if you only want Standard Output and no Standard Error at all, you can use the following command:

dir test.exe 1> myoutput.txt 2>nul

This will result in the same output file as the first example above where you only redirected the Standard Output, but with this command the error won’t echo inside the console. It won’t create an error log file either.

This is useful if you don’t care about any errors and don’t want them to become a nuisance.

You can perform any of the same output commands above from inside a BAT file and the output from that line will go to the output file you specify. This is a useful way to see whether any commands within a BAT file had any errors when they tried to run.

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:

Export Network Settings to a File

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 it 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.

Export Ping Results to a File

ping 192.168.86.1 > "C:\Users\jonfi\Desktop\Ping 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:\Users\jonfi\Desktop. 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 >> \\server\files\officenetsettings.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.

Export Text Results in Terminal

Terminal provides an easy way to create a text file containing the contents of whatever you see in Command Prompt. Although the same redirection operator described above works in Terminal, too, this method is useful for when you didn’t use it.

To save the results from a Terminal window, right-click the tab you’re working in and select Export Text. You can then choose where to save the TXT file.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

Save command output to text file
Save command output to text file
(Image credit: Future)

On Windows 11 and 10, the ability to save the Command Prompt or PowerShell command output to a text file can be helpful in many situations. For instance, exporting the command output for analysis is convenient for troubleshooting a problem. You can also print the return of a command to a text file to save a configuration for documentation purposes and more.

You can always select and right-click the content to copy the output to the clipboard and paste it to a text file. However, the approach requires additional steps, which you can avoid with a single command using the redirected output to the file function.

This guide will walk you through the steps to save the command output to a text file on Command Prompt or PowerShell on Windows 11. (The instructions will also work on Windows 10.)

How to save command output to file using Command Prompt

To save the command output to a text file with Command Prompt, use these steps:

  1. Open Start.
  2. Search for Command Prompt.
  3. Right-click the top result and select the Run as administrator option.
  4. Type the following command to save the output to a text file and press Enter: YOUR-COMMAND > C:\PATH\TO\FOLDER\OUTPUT.txt

In the command, change «YOUR-COMMAND» with your command and «c:\PATH\TO\FOLDER\OUTPUT.txt» with the path and file name to store the output. 

This example exports the system technical specifications to the «laptop_tech_specs.txt» file: systeminfo > C:\laptop_tech_specs.txt

Command Prompt save command output to file

(Image credit: Future)
  1. (Optional) Type the following command to save the output and view results on the screen and press Enter: YOUR-COMMAND > C:\PATH\TO\FOLDER\OUTPUT.txt | type C:\PATH\TO\FOLDER\OUTPUT.txt

In the command, change «YOUR-COMMAND» with your command and «c:\PATH\TO\FOLDER\OUTPUT.txt» with the path and filename to store and view the output. 

This example exports the system technical specifications to the «laptop_tech_specs.txt» file and prints the information on the screen: systeminfo > C:\laptop_tech_specs.txt | type C:\laptop_tech_specs.txt

  • Quick tip: If you have problems viewing the file, you can use the type c:\PATH\TO\FOLDER\OUTPUT.txt command after step No. 3.

Command Prompt export and show output

(Image credit: Future)

Once you complete the steps, the command output will be saved into the text file, which you can review or share with tech support.

How to save command output to file using PowerShell

To save the command output to a text file with PowerShell on Windows 11 or Windows 10, use these steps:

  1. Open Start.
  2. Search for PowerShell.
  3. Right-click the top result and select the Run as administrator option.
  4. Type the following command to save the output to a text file and press Enter: YOUR-COMMAND | Out-File -FilePath C:\PATH\TO\FOLDER\OUTPUT.txt

In the command, change «YOUR-COMMAND» with your command and «c:\PATH\TO\FOLDER\OUTPUT.txt» with the path and file name to store the output.

This example exports the IP address configuration to the «laptop_network_settings.txt» file: ipconfig | Out-File -FilePath C:\laptop_network_settings.txt

PowerShell save output to text file

(Image credit: Future)
  1. (Optional) Type the following command to view the saved output on the screen and press Enter: Get-Content -Path C:\PATH\TO\FOLDER\OUTPUT.txt

In the command, change «c:\PATH\TO\FOLDER\OUTPUT.txt» with the path and file name with the output content. 

This example shows the contents of the «laptop_network_settings.txt» file: Get-Content -Path C:\laptop_network_settings.txt

PowerShell print text file

Source: Windows Central (Image credit: Future)

After you complete the steps, PowerShell will save the result into a text file on your specified location.

More Windows resources

For more helpful articles, coverage, and answers to common questions about Windows 10 and Windows 11, visit the following resources:

  • Windows 11 on Windows Central — All you need to know
  • Windows 10 on Windows Central — All you need to know

All the latest news, reviews, and guides for Windows and Xbox diehards.

Mauro Huculak is technical writer for WindowsCentral.com. His primary focus is to write comprehensive how-tos to help users get the most out of Windows 10 and its many related technologies. He has an IT background with professional certifications from Microsoft, Cisco, and CompTIA, and he’s a recognized member of the Microsoft MVP community.

  • Windows cannot be installed on drive 0 partition 1
  • Windows cannot access the specified device path or file что делать
  • Windows chrome user agent string
  • Windows classic shell for windows 11
  • Windows ce mips или sh4