Windows command output to file

При выполнении каких-либо команд в командной строке или 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 приведены лишь базовые варианты, в действительности возможностей вывода нужных данных при выполнении команд в файл в этом языке присутствует больше. Но, надеюсь, для большинства моих читателей приведённых сведений будет достаточно для их задач.

Save command output to text file

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

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

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

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

How to save command output to file using Command Prompt

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

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

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

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

Command Prompt save command output to file

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

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

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

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

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

Command Prompt export and show output

(Image credit: Future)

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

How to save command output to file using PowerShell

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

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

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

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

PowerShell save output to text file

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

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

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

PowerShell print text file

Source: Windows Central (Image credit: Future)

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

More Windows resources

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

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

Mauro Huculak has been a Windows How-To Expert contributor for WindowsCentral.com for nearly a decade and has over 15 years of experience writing comprehensive guides. He also has an IT background and has achieved different professional certifications from Microsoft, Cisco, VMware, and CompTIA. He has been recognized as a Microsoft MVP for many years.

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

  • To send command line output to a text file on Windows, open Command Prompt (admin) and run “Command-syntax > C:\Output.txt” or “Command-syntax | tee C:\Output.txt” in PowerShell (admin).

On Windows 11, 10, 8, 7, or even older versions, it’s possible to save a command’s output, and in this guide, I will explain how to complete this process. Usually, you open the Command Prompt or PowerShell, run one or a series of commands, then select and copy the output, create a text file, paste the results, and save the file. Although this is a common approach, it takes a lot of steps. You can also take a screenshot or picture with your phone, but these are not the best ways to accomplish this task.

The correct approach is to append the command syntax you want to run with the correct command that Command Prompt and PowerShell offer to save the output to a text file.

In this guide, I will explain the different methods to save the command output to a text file on virtually any version of Windows.

Save command output to a text file on Windows

On Windows, you can export the command output with different commands depending on whether you use Command Prompt or PowerShell.

From Command Prompt

To save the output of a command from Command Prompt, use these steps:

  1. Open Start.

  2. Search for Command Prompt, right-click the top result, and choose the Run as administrator option.

  3. (Option 1) Type the following command to export the command output to a text file and press Enter:

    Command-syntax > C:\Path\to\Export-results.txt

    In the command, replace “Command-syntax” with the command syntax and specify the path and the name of the text file to save the contents. For example, ipconfig > C:\Export-results.txt

    Command Prompt save output to file

  4. (Option 2) Type the following command to export the command and append the result to an existing text file, and press Enter

    Command-syntax >> C:\Path\to\Export-results.txt
  5. (Option 3) Type the following command to capture and view the output in the console and press Enter:

    Command-syntax > C:\Path\to\Export-results.txt | type C:\Path\to\Export-results.txt

The greater-than > redirect operator makes it possible to redirect whatever the outcome of the command is into a text. You’re not limited to text files. You can also export to “.doc,” “.xls,” and other formats.

If you need to create a list of all the files and folders from a specific location, instead of typing one by one, use this command:

  • Dir /b > C:\Output-file.csv

If you need to create a list of specific types of files, use this command:

  • Dir *.doc/b > C:\Output-file.csv

The asterisk (*) represents any name, the kind of file that you want a list from, and (/b) uses bare format (no heading information or summary).

From PowerShell

To save the command output to a text file from PowerShell, use these steps:

  1. Open Start.

  2. Search for PowerShell, right-click the top result, and choose the Run as administrator option.

  3. (Option 1) Type the following command to export the command output to a text file and press Enter:

    Command-syntax | tee C:\Path\to\Export-results.txt

    In the command, replace “Command-syntax” with the command syntax and specify the path and the name of the text file to save the contents. For example, ipconfig | tee C:\Export-results.txt

    PowerShell save output to file

  4. (Option 2) Type the following command to capture and append the result to the end of a file and press Enter:

    Command-syntax | tee -append C:\Path\to\Export-results.txt

The pipeline operator | and tee commands (short for “Tee-Object”) send the capture of the output to the file while showing the result on the console screen. Also, the -append option prevents overriding an existing file by appending the next output to the end of the file.

Why You Can Trust Pureinfotech

The author combines expert insights with user-centric guidance, rigorously researching and testing to ensure you receive trustworthy, easy-to-follow tech guides. Review the publishing process.

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

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как определить версию ос windows на вашем компьютере
  • Как восстановить откатить windows 10
  • Как сделать загрузочную флешку windows 10 из iso образа на linux mint
  • Windows show cpu temp
  • Формат значков на рабочем столе windows 10