How to Use Out-File in PowerShell: Save Output to Files Easily
Use the
Out-File cmdlet in PowerShell to send output from commands or scripts to a file instead of the screen. Simply pipe the output to Out-File followed by the file path, like Get-Process | Out-File C:\temp\processes.txt.Syntax
The basic syntax of Out-File is:
Command | Out-File -FilePath <path> [options]
Where:
- Command: Any PowerShell command producing output.
- -FilePath: Specifies the file path to save the output.
- Options: Additional parameters like
-Appendto add to existing file,-Encodingto set text encoding, and-Widthto control line width.
powershell
Get-Process | Out-File -FilePath C:\temp\processes.txt
Example
This example shows how to save the list of running processes to a text file named processes.txt in the C:\temp folder. It demonstrates capturing command output and writing it to a file.
powershell
Get-Process | Out-File -FilePath C:\temp\processes.txt # To verify, read the file content: Get-Content C:\temp\processes.txt
Output
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
123 10 15000 20000 0.03 1234 1 notepad
234 15 25000 30000 0.10 2345 1 powershell
... (more lines depending on running processes)
Common Pitfalls
Common mistakes when using Out-File include:
- Not specifying the full file path, which may save the file in an unexpected folder.
- Overwriting existing files unintentionally because
Out-Filereplaces files by default. - Using
Out-Filewithout the pipeline, which produces no output. - Confusing
Out-FilewithSet-ContentorAdd-Content, which behave differently.
Example of overwriting vs appending:
powershell
# Overwrites the file "Hello" | Out-File -FilePath C:\temp\example.txt # Appends to the file "World" | Out-File -FilePath C:\temp\example.txt -Append
Quick Reference
Here is a quick summary of useful Out-File parameters:
| Parameter | Description |
|---|---|
| -FilePath | Specifies the path of the file to write output to. |
| -Append | Adds output to the end of the file instead of overwriting. |
| -Encoding | Sets the text encoding (e.g., UTF8, ASCII). |
| -Width | Sets the maximum line width for output formatting. |
| -NoClobber | Prevents overwriting an existing file; throws an error if the file exists. |
Key Takeaways
Use
Out-File to save command output to a file by piping output to it.Always specify the full file path to avoid saving files in unexpected locations.
Use the
-Append parameter to add to existing files instead of overwriting.Remember
Out-File replaces files by default unless -Append or -NoClobber is used.Check file content with
Get-Content after writing to verify output.