Как перенаправить вывод в файл windows

I’m trying to redirect all output (stdout + stderr) of a Windows command to a single file:

C:\>dir 1> a.txt 2> a.txt
The process cannot access the file because it is being used by another process.

Is it possible, or should I just redirect to two separate files?

Mofi's user avatar

Mofi

46.3k17 gold badges81 silver badges145 bronze badges

asked Sep 14, 2009 at 11:20

ripper234's user avatar

ripper234ripper234

223k276 gold badges635 silver badges905 bronze badges

2

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL. More explanation and examples are on the Microsoft documentation page Redirecting error messages from Command Prompt: STDERR/STDOUT.

Mofi's user avatar

Mofi

46.3k17 gold badges81 silver badges145 bronze badges

answered Sep 14, 2009 at 11:23

Anders Lindahl's user avatar

Anders LindahlAnders Lindahl

41.7k9 gold badges90 silver badges93 bronze badges

7

Anders Lindahl’s answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.

REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt

S.S. Anne's user avatar

S.S. Anne

15.2k8 gold badges38 silver badges76 bronze badges

answered May 23, 2013 at 11:59

DelboyJay's user avatar

13

Background info from Microsoft documentation

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

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

Summary

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

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

Example

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

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

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

File Not Found

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

dir file.xxx 2> nul

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

dir file.xxx > output.msg 2> output.err

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

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

bzeaman's user avatar

bzeaman

1,12811 silver badges28 bronze badges

answered Oct 18, 2013 at 18:57

StormeHawke's user avatar

StormeHawkeStormeHawke

5,9875 gold badges45 silver badges74 bronze badges

To add the stdout and stderr to the general logfile of a script:

dir >> a.txt 2>&1

answered Jul 24, 2013 at 10:16

Henk Wiersema's user avatar

1

Correct, file handle 1 for the process is STDOUT, redirected by the 1> or by > (1 can be omitted, by convention, the command interpreter [cmd.exe] knows to handle that).
File handle 2 is STDERR, redirected by 2>.

Note that if you’re using these to make log files, then unless you’re sending the outut to _uniquely_named_ (eg date-and-time-stamped) log files, then if you run the same process twice, the redirected will overwrite (replace) the previous log file.

The >> (for either STDOUT or STDERR) will APPEND not REPLACE the file. So you get a cumulative logfile, showwing the results from all runs of the process — typically more useful.

Happy trails…

falsetru's user avatar

falsetru

358k63 gold badges735 silver badges638 bronze badges

answered Feb 6, 2014 at 4:28

Max Vitesse's user avatar

There is, however, no guarantee that the output of SDTOUT and STDERR are interweaved line-by-line in timely order, using the POSIX redirect merge syntax.

If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.

A dedicated console output logger (I.e. the "StdOut/StdErr Logger" by 'LoRd MuldeR') may be more reliable for such a task.

See: MuldeR’s OpenSource Projects

answered Feb 27, 2018 at 13:30

LigH's user avatar

LigHLigH

511 silver badge4 bronze badges

In a batch file (Windows 7 and above) I found this method most reliable

Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F

Obviously, use whatever commands you want and the output will be directed to the text file.
Using this method is reliable HOWEVER there is NO output on the screen.

answered Sep 12, 2019 at 20:12

PanamaPHat's user avatar

1


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

  • 15.11.2016
  • 84 195
  • 23
  • 12.11.2022
  • 60
  • 56
  • 4

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

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

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

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

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

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

ping 8.8.8.8 > C:\Logs\ping.txt

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

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

ping 8.8.8.8 > C:\Logs\ping.txt & type C:\Logs\ping.txt

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

ping 8.8.8.8 >> C:\Logs\ping.txt

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

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

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

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

I’m trying to redirect all output (stdout + stderr) of a Windows command to a single file:

C:\>dir 1> a.txt 2> a.txt
The process cannot access the file because it is being used by another process.

Is it possible, or should I just redirect to two separate files?

Mofi's user avatar

Mofi

46.3k17 gold badges81 silver badges145 bronze badges

asked Sep 14, 2009 at 11:20

ripper234's user avatar

ripper234ripper234

223k276 gold badges635 silver badges905 bronze badges

2

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL. More explanation and examples are on the Microsoft documentation page Redirecting error messages from Command Prompt: STDERR/STDOUT.

Mofi's user avatar

Mofi

46.3k17 gold badges81 silver badges145 bronze badges

answered Sep 14, 2009 at 11:23

Anders Lindahl's user avatar

Anders LindahlAnders Lindahl

41.7k9 gold badges90 silver badges93 bronze badges

7

Anders Lindahl’s answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.

REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt

S.S. Anne's user avatar

S.S. Anne

15.2k8 gold badges38 silver badges76 bronze badges

answered May 23, 2013 at 11:59

DelboyJay's user avatar

13

Background info from Microsoft documentation

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

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

Summary

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

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

Example

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

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

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

File Not Found

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

dir file.xxx 2> nul

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

dir file.xxx > output.msg 2> output.err

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

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

bzeaman's user avatar

bzeaman

1,12811 silver badges28 bronze badges

answered Oct 18, 2013 at 18:57

StormeHawke's user avatar

StormeHawkeStormeHawke

5,9875 gold badges45 silver badges74 bronze badges

To add the stdout and stderr to the general logfile of a script:

dir >> a.txt 2>&1

answered Jul 24, 2013 at 10:16

Henk Wiersema's user avatar

1

Correct, file handle 1 for the process is STDOUT, redirected by the 1> or by > (1 can be omitted, by convention, the command interpreter [cmd.exe] knows to handle that).
File handle 2 is STDERR, redirected by 2>.

Note that if you’re using these to make log files, then unless you’re sending the outut to _uniquely_named_ (eg date-and-time-stamped) log files, then if you run the same process twice, the redirected will overwrite (replace) the previous log file.

The >> (for either STDOUT or STDERR) will APPEND not REPLACE the file. So you get a cumulative logfile, showwing the results from all runs of the process — typically more useful.

Happy trails…

falsetru's user avatar

falsetru

358k63 gold badges735 silver badges638 bronze badges

answered Feb 6, 2014 at 4:28

Max Vitesse's user avatar

There is, however, no guarantee that the output of SDTOUT and STDERR are interweaved line-by-line in timely order, using the POSIX redirect merge syntax.

If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.

A dedicated console output logger (I.e. the "StdOut/StdErr Logger" by 'LoRd MuldeR') may be more reliable for such a task.

See: MuldeR’s OpenSource Projects

answered Feb 27, 2018 at 13:30

LigH's user avatar

LigHLigH

511 silver badge4 bronze badges

In a batch file (Windows 7 and above) I found this method most reliable

Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F

Obviously, use whatever commands you want and the output will be directed to the text file.
Using this method is reliable HOWEVER there is NO output on the screen.

answered Sep 12, 2019 at 20:12

PanamaPHat's user avatar

1

Время на прочтение
4 мин

Количество просмотров 78K

Очень часто приходилось слышать такое от людей, которые много времени проводят за администрированием и другими IT-забавами.

Я, за не очень долгий опыт реального администрирования пришел к обратному выводу. В консоли (командной строке) В Windows можно выполнять очень много разных операций, которые стандартными возможностями не выполняются или выполняются некорректно/неудобно/долго (нужное подчеркнуть)

Совсем недавно где-то на Хабре промелькнуло высказывание из серии «Не думал, что консоль в Виндах что-то может. Хотелось бы узнать об этом побольше».

Вот так и возникло желание написать небольшую статью про основные возможности консоли.

Про самые стандартные команды консоли можно узнать тривиальным способом:
заходим в cmd и пишем:

help

В сообщении я не буду подробно рассматривать команды типа copy (т.е. совсем тривиальные) так как о них можно прочитать введя команду типа

copy /?

1. Ввод-вывод

Рассмотреть же я попытаюсь команды, которые в основном хэлпе не написаны или описаны недостаточно подробно.
Для начала хотелось бы написать про операторы перенаправления ввода-вывода.
Таковыми операторами являются >, >>, <.
Они нам могут пригодиться как минимум в трех ситуациях:

  • Просмотр логов бат-файла
  • Чтение длинных хелпов по консольным утилитам
  • Подхватывание каких-либо переменных из лежащего рядом файла

При желании примеров можно придумать сколько угодно.

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

команда > имя_файла

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

команда >> имя_файла

С помощью символа < можно прочитать входные данные для заданной команды не с клавиатуры, а из определенного (заранее подготовленного) файла:

команда < имя_файла

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

1. Вывод встроенной справки для команды COPY в файл copy.txt:

COPY /? > copy.txt

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

XCOPY /? >> copy.txt

3. Ввод новой даты из файла date.txt (DATE — это команда для просмотра и изменения системной даты):

DATE < date.txt

2. FOR… DO

Второй командой, которую бы хотелось рассмотреть является FOR ... DO
Эта команда, так же как и многие другие достаточно подробно описана на сайте WindowsFAQ.
Я же хочу остановиться на двух наиболее важных пунктах

2.1 Переменные
  1. %~I
    Расширение %I, которое удаляет окружающие кавычки («»).
  2. %~fI
    Расширение %I до полного имени пути.
  3. %~dI
    Замена %I именем диска.
  4. %~pI
    Замена %I на путь.
  5. %~nI
    Замена %I одним именем файла.
  6. %~xI
    Замена %I расширением имени файла.
  7. %~sI
    Замена путем, содержащим только короткие имена.
  8. %~aI
    Замена %I атрибутами файла.
  9. %~tI
    Замена %I временем модификации файла.
  10. %~zI
    Замена %I размером файла.
  11. %~$PATH:I
    Поиск в каталогах, перечисленных в переменной среды PATH, и замена %I полным именем первого найденного файла. Если переменная среды не определена или поиск не обнаружил файлов, модификатор выдает пустую строку.

Очевидно, что с помощью такого широкого набора переменных мы можем практически полностью отвязаться от индивидуальных особенностей конкретного экземпляра операционной системы и => избежать проблем например из-за того, что система встала на диск E:, а не на C:.

2.2 Работа с файлами

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

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

Данная команда производит разбор каждой строки в файле Myfile.txt, игнорируя строки, начинающиеся с точки с запятой, и передает второй и третий элементы из каждой строки в тело цикла команды FOR. Элементы разделяются запятыми и/или пробелами. Тело инструкции FOR использует %i для получения второго элемента, %j для получения третьего элемента и %k для получения оставшихся элементов в строке. Если имена файлов содержат пробелы, их следует заключать в кавычки (например, «ИмяФайла»). Для использования кавычек необходима команда usebackq. В противном случае кавычки рассматриваются как определение символьной строки для разбора.

Переменная %i объявлена явно в инструкции FOR, а %j и %k объявлены неявно с помощью tokens=. С помощью tokens= можно указать до 26 элементов, если это не вызовет попытки объявить переменную с именем, большим буквы «z» или «Z».

Для разбора вывода команды с помощью помещения параметра МножествоИменФайлов в скобки можно использовать следующую команду:
for /F "usebackq delims==" %i IN (`set`) DO @echo %i

В данном примере перечисляются имена переменных среды в текущем окружении.

Пофантазируем?..

Итак, что нам дают всего эти две команды?

Ну вот возьмем для примера утилиту, которая лежит на сайте Microsoft и называется psexec. Она позволяет нам, зная логин и пароль машины, подключиться к ней и выполнить произвольные действия

в консольном режиме

Допустим, что у нас есть домен Windows и пароль доменного администратора.
Нам нужно подключиться ко всем машинам и удалить все файлы с маской *.mp3 с диска C:.

Для начала — как получить список всех компьютеров сети.
Я это делаю так:

FOR /F "skip=3 delims=\ " %%A IN ('NET VIEW') DO ECHO %%A>>c:\comps.txt

Имеем список всех компов в сети в столбик — как раз в том формате, который принимает psexec.
Правда, будут проблемы с русскими названиями компов, но это ведь не актуальная проблема, да?

Теперь про PsExec. Скачать его можно тут.
Синтаксис описан там же.

Нас интересует вот какая команда
c:\psexec.exe @c:\comps.txt -u username -p password -c MP3DELETE.bat

Содержимое .bat — файла:
cd /d c:\
for /r %%p in (*.mp3) do del %%p

Само собой, задача чисто абстрактная. Мне просто хотелось показать, что консоль в Windows на самом деле весьма могуча и позволяет красиво и удобно решать многие задачи.

А уж как здорово одним нажатием на bat-ник устанавливать пользователям софт в unattended-режиме…

Спасибо за внимание! Жду критики и предложений…

UPD.1 Спасибо большое maxshopen за инвайт и первую карму!
Благодаря ему и всем плюсующим с радостью перенес свою первую статью в свой первый блог — Windows.

UPD.2 Спасибо, Hint

copy con file.txt
Перенаправляет вывод с клавиатуры в файл (CTRL+Z — завершение ввода).
type file.txt >prn
Печает на принтере file.txt

UPD.3 Дамы и Господа!
Осознал, что можно на эту тему еще писать и писать.
У кого-нибудь есть какие-нибудь конкретные пожелания?
Или мне самому тему придумать?
Если пожелания есть, то пишите в кАментах.

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

  • Как перенести vipnet client на другой компьютер windows 10
  • Как переназначить клавиши на клавиатуре windows 10 без программ
  • Как переназначить сочетания клавиш для клавиатуры windows 10
  • Как перенести program files x86 на другой диск windows 10
  • Как переназначить диск для загрузки windows 10