Как записать вывод команды в файл windows

Командная строка - неизменный компонент любой операционной системы Windows, который ...


Windows 10, Windows 11, Windows 7, Windows 8, Windows Server, Windows Vista, Windows XP

  • 15.11.2016
  • 74 750
  • 20
  • 12.11.2022
  • 53
  • 50
  • 3

Как сохранить в текстовый файл вывод командной строки Windows

  • Содержание статьи
    • Использование перенаправления выполнения команд
    • Комментарии к статье ( 20 шт )
    • Добавить комментарий

Командная строка — неизменный компонент любой операционной системы Windows, который берет свое происхождение прямиком от её предка — операционной системы MS-DOS. Данная программа имеет довольно широкие возможности, но сейчас мы поговорим о довольно примитивной вещи — сохранение (по факту — перенаправление) вывода командной строки в текстовый файл.

Почитать о том, как сделать тоже самое в LinuxBSD системах можно в этой статье.

Использование перенаправления выполнения команд

В случае, если необходимо просто сохранить все, что вывела командная строка в текстовый файл, то нужно после введенной команды добавить символ «>», что приведет к созданию текстового файла и весь вывод командной строки отправится туда. Пример:

ping 8.8.8.8 > C:Logsping.txt

Обратите внимание, что командная строка при перенаправлении вывода может создать только текстовый файл, но не папку. Если вы введете несуществующий путь, то получите ошибку!

Как видно, командная строка не вывела никакого результата введенной команды на экран, но зато сохранила все в файл ping.txt. К сожалению, существуют ограничения перенаправления вывода, которые не позволяют одновременно отображать вывод и в окне командной строки, и сохранять их в текстовый файл. Однако, можно воспользоваться хитростью — сразу по завершению выполнения команды вывести содержимое текстового файла на экран с помощью команды type. Получится что-то следующее:

ping 8.8.8.8 > C:Logsping.txt & type C:Logsping.txt

Если требуется файл не записывать (существующий текстовый файл будет перезаписан), а дописывать (существующий текстовый файл будет дополнен), нужно вместо одного символа «>» использовать два — «>>».

ping 8.8.8.8 >> C:Logsping.txt

В случае, если в текстовый файл нужно сохранить так же какой-то текст (например, в составе bat файла), то можно воспользоваться комбинацией с командой echo:

echo Имя компьютера: %computername% > C:Logsping.txt
echo Проверка пинга до google.ru >> C:Logsping.txt
ping google.ru >> C:Logsping.txt

Содержимое получившегося текстового файла будет следующим:

Для того, чтобы вывод был только в текстовый файл (без показа в окне командной строки), нужно вставить первой строкой в bat файле команду @echo off

Перенаправление ввода-вывода в 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

I’d like to easily save the log of the Windows command prompt into a file. Is there any alternative to select everything and right-click on copy?

Kara's user avatar

Kara

6,06516 gold badges51 silver badges57 bronze badges

asked Jan 24, 2013 at 11:45

Luis Andrés García's user avatar

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:output.txt
echo Hello again! >>C:output.txt

or

mybatchfile.bat >C:output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

answered Jan 24, 2013 at 11:49

Bali C's user avatar

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on «Windows PowerShell»

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

answered Sep 25, 2014 at 8:22

Mr.Hunt's user avatar

Mr.HuntMr.Hunt

4,8132 gold badges20 silver badges28 bronze badges

3

In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file.
Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).

answered Nov 29, 2019 at 20:35

oscar_ceja's user avatar

Создание и чтение текстовых файлов в командной строкеЕсли вы оказались без доступа к чему-либо кроме командной строки или Windows PowerShell и по какой-то причине вам требуется возможность создания или чтения текстовых файлов, это вполне реализуемо, причем более чем одним методом.

В этой инструкции подробно о работе с текстовыми файлами в командной строки или PowerShell (разумеется, можно и в Терминале Windows) — создание и сохранение текстовых файлов, их вывод и чтение в консоли.

Создание текстовых файлов в командной строке

Возможность создания текстовых файлов доступна как в командной строке (cmd.exe), так и в PowerShell. Начнем с первого варианта.

Во всех случаях учитывайте, что при использовании кириллицы потенциально возможны проблемы с кодировкой, а в некоторых случаях кодировка может отличаться при использовании разных команд.

Команда ECHO

Команда командной строки echo предназначена для вывода текстовых сообщений в окне консоли, например, при выполнении сценария в bat-файле, но может быть использована и для вывода текста в файл, благодаря возможности использования оператора «>» для перенаправления вывода из консоли в файл.

Пример команды:

echo Содержимое текстового файла > file.txt

В результате её выполнения в текущей рабочей папке командной строки будет создан файл с именем file.txt и содержимым «Содержимое текстового файла».

Создание текстового файла с помощью команды echo

COPY CON

Команда copy с параметром con позволяет скопировать содержимое консоли в файл. Использование возможности будет состоять из следующих шагов:

  1. Введите команду
    copy con имя_файла.txt

    файл не будет создан, но после выполнения указанной команды у вас появится возможность набрать содержимое этого файла, которое по завершении процесса будет в него сохранено.

  2. Курсор переместится на строчку ниже, и вы сможете набирать текст так, как делаете это обычно, включая перенос строки. Создание текстового файла с помощью copy con
  3. Для завершения набора и сохранения текстового файла нажмите сочетание клавиш Ctrl+Z, а затем — Enter. Это добавит отметку конца файла и сохранит его в текущей папке с указанным на 1-м шаге именем. Сохранение текстового файла с помощью copy con

Создание текстового файла в PowerShell

PowerShell также имеет набор встроенных командлетов для сохранения текстовых данных в файл.

Out-File

Использование Out-File в PowerShell по своей функциональности сходно с оператором перенаправления вывода в командной строке. Вывод консоли перенаправляется в заданный файл.

Пример использования:

"Текстовая строка" | Out-File -FilePath .file.txt

В этом примере в текущей папке PowerShell будет создан файл с именем file.txt и содержимым «Текстовая строка».

New-Item

Создание нового текстового файла в PowerShell возможно с помощью командлета New-Item. Пример команды, в которой создается текстовый файл file.txt, содержащий «Текстовая строка» в текущем расположении:

New-Item -Path . -Name "file.txt" -ItemType "file" -Value "Текстовая строка"

Создание текстового файла с помощью New-Item в PowerShell

Set-Content и Add-Content

Ещё два командлета PowerShell для работы с текстовыми файлами:

  • Set-Content — перезаписывает содержимое файла
  • Add-Content — добавляет содержимое в конце выбранного файла

Их использование можно увидеть на примере следующей команды:

Add-Content -Path .file.txt -Value "Ещё одна текстовая строка"

Добавление текста к файлу в PowerShell

Вывод (чтение) текстового файла в командной строке и PowerShell

Теперь перейдем к способам просмотреть текстовые файлы в командной строке или PowerShell. Как и в предыдущем случае, учитывайте, что для файлов, содержащих кириллицу, возможны проблемы с отображением символов в правильной кодировке.

TYPE

Самый простой вариант — использование команды TYPE с указанием пути к файлу, который нужно отобразить в консоли, например:

type file.txt

Вывод текстового файла с помощью команды type

MORE

Если файл объемный и содержит большое количество строк, используйте команду more, например:

more file.txt

Выполнив команду, вы увидите часть содержимого текста, которая помещается в окне консоли, далее вы можете использовать следующие клавиши:

Вывод текстового файла с помощью команды more

  • Enter — для отображения следующей строки файла.
  • Пробел — для отображения следующих строк документа, которые поместятся в активное окно консоли.
  • P — Показать следующие N строк. После нажатия этой клавиши с последующим указанием количества строк, будет выведено соответствующее количество строк текстового документа.
  • S — пропустить следующие N строк, работает аналогично предыдущему варианту.
  • Клавиша «=» — для отображения текущего номера строки.
  • Q — для прекращения выполнения команды more.

Get-Content

Вывести содержимое текстового файла в PowerShell можно с помощью Get-Content с указанием пути к файлу, например:

Get-Content file.txt

Чтение текстового файла с помощью Get-Content в PowerShell

Также вы можете выводить определенные строки файла, с помощью команд вида (вывод первых или последних 10 строк соответственно):

Get-Content file.txt | Select-Object -First 10
Get-Content file.txt | Select-Object -Last 10

Или присвоить содержимое файла переменной и вывести конкретную строку:

$file_text = Get-Content file.txt
$file_text[2]

Текстовый редактор edit.com в Windows

Помимо использования ручного ввода команд, вы можете использовать консольные текстовые редакторы — сторонние в версиях для Windows, такие как Vim, Nano, Kinesics Text Editor или даже старый встроенный edit.com (может отсутствовать в вашей версии системы и требовать патча NTVDMx64).

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,2383 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

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,2383 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

На чтение 6 мин. Опубликовано 15.12.2019

Содержание

  1. Вывод в файл txt результатов выполнения команды в cmd
  2. Описание
  3. Другие статьи:
  4. Комментарии:

Вывод в файл txt результатов выполнения команды в cmd

Иногда возникает желание зафиксировать результат выполнения команды в cmd . Как правило , такое желание возникает , когда текст не помещается в окно командной строки ( cmd ).

Синтаксис для записи результата выполнения команды простой .

Команда_с_ключами > путь_к_файлу имя_файла.txt

То есть вначале пишется команда со всеми ключами и параметрами , а сразу после последнего символа ставиться символ > потом пробел и пишется путь и имя файла , в который будет сохранен результат . Результат будет сохранен в файл без вывода на экран . Файл сохраняется в кодировке DOS-866.

Для примера , выполним команду ping itindustry-spb.ru с записью на диск D в файл ping.txt

Для этого в командной строке выполняем команду ping itindustry-spb.ru > D: ping.txt

Ниже показан результат выполнения этой команды

Командная строка в операционной системе Windows довольно удобный инструмент, который позволяет делать многие вещи намного быстрее. Но она имеет один недостаток с ней нельзя работать также как с другими программами. Текстовый интерфейс требует знания специальных команд. В данной статье мы рассмотрим два способа сохранения вывода командной строки.

Часто возникает необходимость сохранить вывод из командной строки.

Способ № 1. Сохранения текста из командной строки в файл.

Если после команды добавить >> и ввести адрес текстового документа, то результаты выполнения данной команды будут сохранены в этом файле.

Например, вводим ipconfig /all >> d:cmd.txt и жмем ввод для выполнения команды. После того как команда будет выполнена в текстовом файле cmd.txt на диске d: будут сохранены все результаты. При этом в текст будет закодирован с помощью кодировки IBM CP866. Поэтому для того чтобы его открыть придётся использовать сторонние приложения, например программу Akelpad.

Способ № 2. Сохранение текста из командной строки в буфер обмена.

С помощью команды clip вывод командной строки можно направить в буфер обмена. Для этого после команды нужно добавить: | clip (пробел, вертикальная черта и команда clip) .

Например, вводим ipconfig /all | clip и жмем ввод для выполнения команды. Когда выполнение команды будет завершено, результаты будут помещены в буфер обмена. Для того чтобы воспользоваться этими результатами достаточно вставить текст в любом текстовом редакторе с помощью всем известной комбинации клавиш Cntrl+V.

Способ № 3. Скопировать текст из командной строки.

Последний способ позволяет сохранить не только результаты работы команды, но и всю остальную информацию из командной строки.

Чтобы это сделать кликаем правой кнопкой мышки по командной строке и вызываем контекстное меню. В открывшемся меню выбираем пункт «Пометить».

После этого выделяем текст в командной строке с помощью мышки и нажимаем на клавишу Enter. После нажатия на Enter выделение исчезнет, а текст будет скопирован в буфер обмена.

Командная строка — неизменный компонент любой операционной системы Windows, который берет свое происхождение прямиком от её предка — операционной системы MS-DOS. Данная программа имеет довольно широкие возможности, но сейчас мы поговорим о довольно примитивной вещи — сохранение (по факту — перенаправление) вывода командной строки в текстовый файл.

Описание

В случае, если необходимо просто сохранить все, что вывела командная строка в текстовый файл, то нужно после введенной команды добавить символ «>», что приведет к созданию текстового файла и весь вывод командной строки отправится туда. Пример:

Как видно, командная строка не вывела никакого результата введенной команды на экран, но зато сохранила все в файл ping.txt. К сожалению, существуют ограничения перенаправления вывода, которые не позволяют одновременно отображать вывод и в окне командной строки, и сохранять их в текстовый файл. Однако, можно воспользоваться хитростью — сразу по завершению выполнения команды вывести содержимое текстового файла на экран с помощью команды type. Получится что-то следующее:

Если требуется файл не записывать (существующий текстовый файл будет перезаписан), а дописывать (существующий текстовый файл будет дополнен), нужно вместо одного символа «>» использовать два — «>>».

Почитать о том, как сделать тоже самое в LinuxBSD системах можно в этой статье.

Другие статьи:

Комментарии:

    • rekill

    • 22.08.2019 15:06

    У меня есть программа на Visual Studio C++ она выводит числа и текст,можно ли как-то сохранять все что выводит в текстовый документ?
    Искал в интернете ничего не нашел про вывод в текстовый документ именно в C++.

    Если у Вас программа в Visual Studio, то есть, вы обладаете её исходными кодами — то Вам нужно модифицировать её исходный код, добавив помимо вывода чисел и текста на экран, сохранение в текстовый файл.

    А ещё такой вопрос. В Файл всё Сохраняется нечитабельно, можно исправить с помощью той же командной строки?

    Самый простой вариант, который без проблем подойдет для большинства случаев — это сперва выполнить команду chcp 855 . Единственный минус — при этом все будет на английском.

    Добрый день.
    Тогда можно можно ещё и на ФТП грузить результат ?)

    Можно, но для этого нужно будет лучше написать отдельную статью. Как руки дойдут — обязательно сделаю!

    Не совсем понял про какие переменные для ping или systeminfo идет речь, поэтому лучше уточните, что именно вы хотите сделать.

    Если же речь идет про переменные, вроде %COMPUTERNAME% , то их можно найти выполнив в командной строке команду set , либо по запросу «Переменные среды» в интернете.

    ДА, лучше, благодарю. Напоследок, где поточнее можно почитать про другие переменные, которые может использовать тот же ping или systeminfo (нужно было для systeminfo), а то в хелпе к systeminfo описаны лишь несколько базовых операций, а про переменные ни слова.

    А вам не проще будет использовать имена компьютеров в имени файлов отчета? Для этого используйте переменную %COMPUTERNAME% в названии файла, в который идет сохранение, например:

    Подскажите, а как можно сохранять файл отчета с новыми номерами, чтобы они шли по порядку друг за другом?
    То есть, я сохраняю файл отчета, то же самое проделывается на других машинах и все сохраняется в одну папку с одинаковым именем файла (потому что сделано через bat), как сделать, чтобы файл нумеровался и не заменялся.

    Что подразумевается под общим диском? Если сетевой диск, то у него должна быть конкретная буква, под которой он смонтирован в системе, и нужно проделать все то же самое, о чем написано в статье:

    ping 8.8.8.8 > Z: est.txt

    Если под общим диском подразумевается сетевая «шара», то и тут нужно делать все тоже самое, например:

    ping 8.8.8.8 > serverupload est.txt

    А возможно ли записать файл с результатом на общий диск?

Понравилась статья? Поделить с друзьями:
  • Как записать винду на флешку windows 7
  • Как записать весь экран в windows 10
  • Как записать виндовс 8 на флешку для установки windows
  • Как записать вебинар с экрана компьютера со звуком windows 10
  • Как записать видеофайлы на диск на windows 10