Windows cmd redirect output to file

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

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

В этой инструкции подробно о том, как выводить результаты выполнения команд Windows не только в окне консоли, но и в текстовый файл на диске. На близкую тему: Способы создания текстового файла в командной строке и PowerShell.

Командная строка

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

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

  1. Первый вариант — простой вывод в файл. При этом если файл уже существует, он будет перезаписан, а в окне консоли вывод команды не отобразится:
    команда > путь_к_файлу

    Пример вы можете увидеть на скриншоте ниже.

    Команда для вывод в текстовый файл в командной строке

  2. Второй метод не затирает предыдущее содержимое файла, если оно уже есть, а добавляет вывод команды к уже имеющемуся в файле содержимому. Как и в предыдущем случае в окне консоли результат отображаться не будет:
    команда >> путь_к_файлу

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

    Добавление результатов вывода к текстовому файлу в командной строке

  3. Если требуется вывод в файл с одновременным выводом в окне командной строки, можно использовать следующий подход:
    команда >> путь_к_файлу | type путь_к_файлу
    Вывод в текстовый файл и в консоль

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

Windows PowerShell

Если команды выполняются в PowerShell, вы можете использовать команду Tee-Object следующими способами:

  1. Вывод результатов команды в текстовый файл и консоль с перезаписыванием данных в файле:
    команда | tee путь_к_файлу
    Вывод в текстовый файл с помощью Tee Object

  2. Вывод результатов команды в файл с добавлением вывода к имеющемуся содержимому файла:
    команда | tee -append путь_к_файлу
  3. Если нужно вывести в файл результаты выполнения ряда команд, включая сообщения об ошибках, вы можете использовать следующих подход:
    Start-Transcript -Path "путь_к_файлу"
    ваши команды
    Stop-Transcript
    Вывод в текстовый файл с помощью Start-Transcript

В части PowerShell приведены лишь базовые варианты, в действительности возможностей вывода нужных данных при выполнении команд в файл в этом языке присутствует больше. Но, надеюсь, для большинства моих читателей приведённых сведений будет достаточно для их задач.

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

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

How Windows Command Prompt Output Works

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

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

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

Redirect Standard Output Write to New File

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

To do this, open the command prompt and type:

dir test.exe > myoutput.txt

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

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

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

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

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

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

Redirect Standard Output Writes to the Same File

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

dir test.exe >> myoutput.txt

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

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

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

Redirect Standard Error To a File

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

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

In this example, you’ll type the command: 

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

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

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

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

Redirect All Output Writes to a Same File

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

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

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

Here’s how this command works:

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

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

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

Silencing Standard or Error Output Streams

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

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

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

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

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

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

Related Posts

  • How to Fix a “This file does not have an app associated with it” Error on Windows
  • How to Fix an Update Error 0x800705b4 on Windows
  • How to Resolve “A JavaScript error occured in the main process” Error on Windows
  • How to Fix the Network Discovery Is Turned Off Error on Windows
  • How to Change Folder Icons in Windows

Rob van der Woude's Scripting Pages

Display & Redirect Output

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

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

Display text

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

ECHO Hello world

This will show the following text on screen:

Hello world

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

Streams

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

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

  • Standard Output
  • Standard Error
  • Console

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

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

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

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

DIR /S | MORE

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

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

Redirection

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

ECHO Hello world>NUL

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

Now try this (note the typo):

EHCO Hello world>NUL

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

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

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

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

A short demonstration. Try this command:

ECHO Hello world 2>NUL

What you should get is:

Hello world

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

Now make a typo again:

EHCO Hello world 2>NUL

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

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

DIR > NUL

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

C:\>test.bat

C:\>DIR  1>NUL

C:\>_

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

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

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

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

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

C:\>_

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

test.bat > NUL

and you should see:

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

C:\>_

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

Next, run:

test.bat 2> NUL

and you should see:

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

C:\>_

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

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

test.bat > NUL 2>&1

and you should see:

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

C:\>_

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

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

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

Redirect «all» output to a single file:

Run:

test.bat > test.txt 2>&1

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

This text goes to the Console

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

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

Redirect errors to a separate error log file:

Run:

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

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

This text goes to the Console

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

This text goes to Standard Output

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

This text goes to Standard Error

Nothing is impossible, not even redirecting the Console output.

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

The general idea was this:

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

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

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

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

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

START command > logfile

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

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

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

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

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

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

command > logfile

and the command line would be:

START batchfile

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

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

page last modified: 2016-09-19; loaded in 0.0010 seconds

  • SS64
  • CMD
  • How-to

How-to: Redirection

command > filename
command
>&n
 
Redirect command output to a file
Redirect command output to the input of handle n
 
command >> filename
 
APPEND into a file
 
command < filename
command
<&n
 
Type a text file and pass the text to command.
Read input from handle n and write it to command.
 
commandA | commandB
 
Pipe the output from commandA into commandB
 
commandA & commandB Run commandA and then run commandB
commandA && commandB Run commandA, if it succeeds then run commandB
commandA || commandB Run commandA, if it fails then run commandB

commandA && commandB || commandC

If commandA succeeds run commandB, if commandA fails run commandC
If commandB fails, that will also trigger running commandC.

Success and failure are based on the Exit Code of the command.
In most cases the Exit Code is the same as the ErrorLevel

For clarity the syntax on this page has spaces before and after the redirection operators, in practice you may want to omit those to avoid additional space characters being added to the output. Echo Demo Text> Demofile.txt

Numeric handles:

STDIN  = 0  Keyboard input
STDOUT = 1  Text output
STDERR = 2  Error text output
UNDEFINED = 3-9 (In PowerShell 3.0+ these are defined)

When redirection is performed without specifying a numeric handle, the the default < redirection input operator is zero (0) and the default > redirection output operator is one (1). This means that ‘>‘ alone will not redirect error messages.

   command 2> filename       Redirect any error message into a file
   command 2>> filename      Append any error message into a file
  (command)2> filename       Redirect any CMD.exe error into a file
   command > file 2>&1       Redirect errors and output to one file
   command > fileA 2> fileB  Redirect output and errors to separate files

   command 2>&1 >filename    This will fail!

Redirect to NUL (hide errors)

   command 2> nul            Redirect error messages to NUL
   command >nul 2>&1         Redirect error and output to NUL
   command >filename 2> nul  Redirect output to file but suppress error
  (command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors

Any long filenames must be surrounded in «double quotes».
A CMD error is an error raised by the command processor itself rather than the program/command.

Some commands, (e.g. COPY) do not place all their error mesages on the error stream, so to capture those you must redirect both STDOUT and
STDERR with command > file 2>&1

Redirection with > or 2> will overwrite any existing file.

You can also redirect to a printer with > PRN or >LPT1 or to the console with >CON

To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<

Redirection — issues with trailing numbers

Redirecting a string (or variable containing a string) will fail to work properly if there is a single numeral at the end, anything from 0 to 9.
e.g. this will fail:
Set _demo=abc 5
Echo %_demo%>>demofile.txt

One workaround for this is to add a space before the ‘>>’ but that space will end up in the output.
Moving the redirection operator to the front of the line completely avoids this issue, but is undocumented syntax.:

Set _demo=abc 5
>>demofile.txt Echo %_demo%

Create a new file

Create an empty file using the NUL device:

Type NUL >EmptyFile.txt
or
Copy NUL EmptyFile.txt
or
BREAK > EmptyFile.txt

Multiple commands on one line

In a batch file the default behaviour is to read and expand variables one line at a time, if you use & to run multiple commands on a single line, then any variable changes will not be visible until execution moves to the next line. For example:

 SET /P _cost=»Enter the price: » & ECHO %_cost%

This behaviour can be changed using SETLOCAL EnableDelayedExpansion

Redirect multiple lines

Redirect multiple lines by bracketing a set of commands:

(
  Echo sample text1
  Echo sample text2
) > c:\logfile.txt

Unicode

The CMD Shell can redirect ASCII/ANSI (the default) or Unicode (UCS-2 le) but not UTF-8.
This can be selected by launching CMD /A or CMD /U

In Windows 7 and earlier versions of Windows, the redirection operator ‘>’ would strip many Extended ASCII /Unicode characters from the output.
Windows 10 no longer does this.

Pipes and CMD.exe

You can redirect and execute a batch file into CMD.exe with:

CMD < sample.cmd

Surprisingly this will work with any file extension (.txt .xls etc) if the file contains text then CMD will attempt to execute it. No sanity checking is performed.

When a command is piped into any external command/utility ( command | command ) this will instantiate a new CMD.exe instance.
e.g.
TYPE test.txt | FIND «Smith»

Is in effect running:

TYPE test.txt | cmd.exe /S /D /C FIND «Smith»

This has a couple of side effects:
If the items being piped (the left hand side of the pipe) include any caret escape characters ^ they will need to be doubled up so that they survive into the new CMD shell.
Any newline (CR/LF) characters in the first command will be turned into & operators. (see StackOverflow)

On modern hardware, starting a new CMD shell has no noticable effect on performance.

For example, this syntax works, but would fail if the second or subsequent (piped) lines were indented with a space:
@Echo Off
Echo abc def |^
Find «abc» |^
Find «def»> outfile.txt

Multi-line single commands with lots of parameters, can be indented as in this example:

Echo abc def ^
  ghi jkl ^

  mno pqr

Redirection anywhere on the line

Although the redirection operator traditionally appears at the end of a command line, there is no requirement that it do so.
All of these commands are equivalent:

Echo A B>C
Echo A>C B
Echo>C A B
>C Echo A B

All of them Echo «A B» to the file «C».

If the command involves a pipe such as DIR /b | SORT /r then you will still want to put the redirection at the end so that it captures the result of the SORT, but there are some advantages to putting the redirection at the start of the line.

Code like this:

Set _message=Meet at 2
Echo %_message%>schedule.txt

Will inadvertently interpret the “2” as part of the redirection operator.

One solution is to insert a space:

Echo %_message% >schedule.txt 

This assumes that the space won’t cause a problem. If you’re in a case where that space will indeed cause a problem, you can use the trick above to move the redirection operator to a location where it won’t cause any trouble:

>schedule.txt Echo %_message%  

Example via Raymond Chen

The idea of redirection anywhere in the line was first introduced in version 2 of sh, written by Ken Thompson in 1972.

Exit Codes

If the filename or command is not found then redirection will set an Exit Code of 1

When redirecting the output of DIR to a file, you may notice that the output file (if in the same folder) will be listed with a size of 0 bytes. The command interpreter first creates the empty destination file, then runs the DIR command and finally saves the redirected text into the file.

The maximum number of consecutive pipes is 2042

Examples

   DIR >MyFileListing.txt
   
   DIR /o:n >"Another list of Files.txt"

   DIR C:\ >List_of_C.txt 2>errorlog.txt

   DIR C:\ >List_of_C.txt & DIR D:\ >List_of_D.txt

   ECHO y| DEL *.txt

   ECHO Some text ^<html tag^> more text

   COPY nul empty.txt

   MEM /C >>MemLog.txt

   Date /T >>MemLog.txt

   SORT < MyTextFile.txt

   SET _output=%_missing% 2>nul
   
   FIND /i "Jones" < names.txt >logfile.txt

   (TYPE logfile.txt >> newfile.txt) 2>nul

“Stupidity, outrage, vanity, cruelty, iniquity, bad faith, falsehood,
we fail to see the whole array when it is facing in the same direction as we” ~ Jean Rostand (French Historian)

Related commands

CON — Console device.
conIN$
and conOUT$ behave like stdin and stdout, or 0 and 1 streams but only with internal commands.
SORT — Sort input.
CMD Syntax
TYPE — Display the contents of one or more text files.
Command Redirection — Microsoft Help page (archived)
Successive redirections explained (1>&3 ) — Stack Overflow.
Equivalent PowerShell: Redirection — Spooling output to a file, piping input.
Equivalent bash command (Linux): Redirection — Spooling output to a file, piping input.


Copyright © 1999-2025 SS64.com
Some rights reserved

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не монтируется образ iso windows 11
  • Размытый текст в приложениях windows 11
  • C windows system32 searchfilterhost exe
  • Компьютер не видит обновления windows 7
  • Установка windows server 2016 на ноутбук