11/21/2024 | News release | Distributed by Public on 11/21/2024 12:01
Anyone familiar with PowerShell knows that the output of PowerShell commands is displayed in the terminal by default. However, there may be situations where you would want to redirect or save output to a file.
In short, redirecting or saving PowerShell output increases productivity, helps with debugging, provides useful logs, and facilitates automation, especially in complex workflows or when working with large datasets.
The PowerShell write to text file method commonly uses the Out-File cmdlet to send command results (output) directly to a file. In its simplest form, Out-File requires specifying a path and filename to write the output to.
By default, the cmdlet overwrites an existing file if one by the same name exists at the specified path, or creates a new one if it does not exist.
Here’s the basic syntax for the Out-File cmdlet:
Out-File [-FilePath][[-Encoding] ] [-Append] [-Force] [-NoClobber] [-Width ] [-NoNewline] [-InputObject ] [-WhatIf] [-Confirm] [ ]
The PowerShell Out-File cmdlet accepts the following parameters:
Parameter | Description |
-Filepath | Sets the path and name of the output file |
-Encoding | Sets the encoding for the output file. Options include ASCII, UTF8, UTF7, Unicode, etc. Default value is utf8NoBOM. |
-Append | Adds output to the end of the file without overwriting existing content |
-Force | Overrides read-only attribute and overwrites an existing read-only file. This parameter does not override security restrictions. |
-NoClobber | Prevents overwriting an existing file. By default, if a file exists in the specified path, the Out-File cmdlet overwrites the file without warning. |
-Width | Limits the number of characters on each line in the output file (default 80). Any additional characters are truncated, not wrapped. |
-NoNewLine | Specifies that the content written to the output file does not end with a newline character. No spaces or newlines are inserted between the output strings and no newline is added after the last output string. |
-InputObject | Specifies the objects to be written to the file. Type a command or expression that gets the objects or enter a variable that contains the objects. |
-WhatIf | Runs the cmdlet in test mode to show the expected results of the cmdlet |
-Confirm | Prompts for confirmation before running the cmdlet |
To write output directly to a file rather than displaying it on the screen, you can use the PowerShell write output to file approach by appending the Out-File cmdlet to a PowerShell command or variable. This technique also works for writing a text string to a file by appending Out-File directly to the string.
To retrieve a list of running processes and use the PowerShell save output to file method, save the output to a text file named “Processes” in the C:\Temp folder with the following example:
Get-Process | Out-File -FilePath C:\Temp\processes.txt
Here, the Get-Process cmdlet will list all the running processes. With PowerShell pipe output to file functionality, you can take command output and immediately save it to a text file for later analysis.
To write a string using the PowerShell write string to file method, such as adding “Hello, World!” to a text file named “Test” at the C:\Temp location, use the following cmdlet:
"Hello, World!" | Out-File -FilePath C:\Temp\Test.txt
If the file doesn’t exist, it will be created. If it does exist, the content will be overwritten by default.
You can also use the Out-File cmdlet with a variable. For example:
$variable | Out-File -FilePath "C:\path\to\file.txt"
Here $variable is the variable that holds the data (e.g., a PowerShell output to text file or command output) you want to send to a file.
Redirection Operators (> and >>) in PowerShell are a simple and quick alternative to the Out-File cmdlet, enabling you to redirect output to a file.
These operators also have other uses like redirecting error or verbose output streams, which is beyond the scope of this article.
The basic syntax for using the operators is as follows:
> # Overwrites
>> # Appends
Notice that the redirect operators do not use any parameters.
This cmdlet writes the output of Get-Process to the Processes.txt file, overwriting any existing content in case a file with this name already exists at the destination.
Get-Process > C:\Temp\Processes.txt
This cmdlet appends the current date and time to the end of the log.txt file without overwriting existing content.
Get-Date >> C:\Temp\log.txt
If a file named log.txt does not exist at the specified path, it creates the file and writes the current date and time to it.
Both the Out-File cmdlet and redirect operators can write and append the PowerShell output to a file. Key differences between the two are discussed below.
Feature | Out-File Cmdlet | Redirection Operators (> and >>) |
Parameters | Accepts parameters | Does not accept parameters |
Overwriting Behavior | Default is overwrite; uses -Append for appending and -NoClobber to avoid overwriting | > overwrites, >> appends No built-in control to prevent overwriting |
Encoding Control | Allows specifying encoding with -Encoding | Limited encoding control (UTF-8 in PowerShell 6+, Unicode in older versions) |
Width Control | Supports setting line width with -Width | No control over line width |
Error Handling | Only successful results are exported, so warnings or errors are not written to the file | Can specify which stream you want to export, like success, error, warning, etc. |
Usage in Scripts | Best for scripts that require more control over output | Quick and convenient for simple redirection |
In comparison, the Out-File cmdlet is more versatile and ideal for complex scripts, with options for encoding, width, and overwrite control. Redirection operators, however, are fast and convenient for quick output jobs that do not require customization. Following is a brief guide on when you should use each.
By default, the Out-File cmdlet overwrites an existing file if one by the same name exists at the specified path, or creates a new file if it does not.
To prevent overwriting an existing file, you can use the PowerShell write to file append method in one of two ways:
Use the -Append parameter with the Out-File cmdlet to add the new output to the end of the specified file without overwriting its existing content. This is particularly useful when, for example, you want to log events incrementally without losing previous data.
This command appends the five most recent entries from the System log to the event_log.txt file.
Get-EventLog -LogName System -Newest 5 | Out-File -FilePath C:\Temp\event_log.txt -Append
You can also use the redirection operator >> to append output to an existing file. In the following example, the status and details of services on your local machine are appended to the contents in the log.txt file.
Get-Service >> C:\Temp\log.txt
Use the -NoClobber parameter with the Out-File cmdlet to prevent overwrites. Hence, if a file with the same name exists at the specified location, PowerShell will not overwrite it and throw an error. This helps protect important files.
The following command will attempt to create a file named log.txt in the Temp folder. But if a file by this name already exists, an error will be displayed and the output will not be saved to file.
Get-Service | Out-File -FilePath C:\Temp\log.txt -NoClobber
Sometimes you are unable to overwrite the contents of an existing file with the output of a PowerShell cmdlet, as the file is read-only. In a situation such as this, use the -Force parameter with the Out-File cmdlet to overwrite read-only files.
This cmdlet writes the services information to the Services.txt file, ensuring that if the Services.txt already exists, it will be overwritten, even if it is read-only.
Get-Service | Out-File -FilePath C:\Temp\Services.txt -Force
PowerShell’s Out-File cmdlet provides options to customize output formatting and encoding.
The Out-File cmdlet may not display output as expected, particularly when the output has multiple columns. For a formatted, readable output, you can adjust the width or use the Format-Table cmdlet.
Use the -Width parameter with Out-File to specify the line width for the output file (80 characters is default).
This cmdlet writes the services information to the Services.txt file, while setting the line width to 200 characters. This allows for wider output without wrapping.
Get-Service | Out-File -FilePath C:\Temp\Services.txt -Width 200
Use the Format-Table cmdlet to structure data before sending it to the Out-File cmdlet.
This cmdlet uses Format-Table -AutoSize to adjust the column widths automatically for readability.
Get-Service | Format-Table -AutoSize | Out-File -FilePath C:\Temp\Services.txt
Encoding output in PowerShell when using the Out-File cmdlet ensures that the data is correctly interpreted, displayed, and compatible across different systems and applications.
The -Encoding parameter helps specify how output text is encoded in the file. Common encoding types include:
It is a good idea to use UTF-8 encoding if the output file contains special characters or the file will be used in environments where UTF-8 is the standard encoding.
This cmdlet retrieves a list of services on the system and outputs the information to the Services.txt file while setting the file encoding to UTF-8.
Get-Service | Out-File -FilePath C:\Temp\Services.txt -Encoding UTF8
ASCII encoding is commonly used for simpler text files.
This cmdlet retrieves a list of services on the system and pipes the outputs to the Services.txt file. The -Encoding parameter is used to convert the output to ASCII format.
Get-Service | Out-File -FilePath C:\Temp\Services.txt -Encoding ASCII
The Out-File cmdlet writes the successful result of your command or script to a file. But it does not write errors, warnings, or specific types of messages to files. This can be achieved with the redirect operator, that enables you to specify which stream you want to output to a file.
Operator | Description / Stream | Write cmdlet |
> | Success only | Write-Output |
2> | Error only | Write-Error |
3> | Warning only | Write-Warning |
4> | Verbose only | Write-Verbose |
5> | Debug only | Write-Debug |
6> | Information only | Write-Information |
*> | All |
This command attempts to list (ls) a file named Readme. It looks for the file in the current directory if you do not specify a path. If the file does not exist, it generates an error message. The 2> operator redirects this error to a file called error.log. As a result, the error is not displayed on screen but saved in error.log in the Temp folder.
ls Readme 2> C:\Temp\error.log
In PowerShell, the warning stream is stream number 3. You can use 3> to redirect warnings to a file: It is as:
# Command that generates a warning
3> C:\Temp\warning_log.txt
The Set-Content and Add-Content cmdlets are another way to write output to file.
Use the Set-Content cmdlet to write or replace the content of a file with new content.
This cmdlet overwrites the existing content in the Test.txt file. The -Value parameter specifies the content or text that will replace the existing content.
Set-Content -Path C:\Temp\Test.txt -Value "Add content here"
Use the Add-Content cmdlet to add content to a file, which means that you can append new data to an existing file without overwriting it. Add-Content can also append content to multiple files at once.
Just like the Out-File cmdlet and redirect operator, the Add-Content cmdlet creates a new file if a file with the same name does not exist.
This cmdlet adds new text to the Test.txt file. The -Value parameter specifies the content or text you want to append to the file.
Add-Content -Path C:\Temp\Test.txt -Value "New line to add"
If the file is read-only, you must use the -Force parameter to allow content to be added.
To add the same content to multiple files, you have several options.
This cmdlet adds the current date to all .txt files in the Temp folder, except in the file with test in the file name:
Add-Content -Path C:\Temp\files\*.txt -Value (Get-Date) -Exclude "test*"
This command adds multiple lines of text to the Test.txt file.
$lines = @( "Line 1: Details", "Line 2: Specific Details" ) Add-Content -Path C:\Temp\Test.txt -Value $lines
You can use .NET classes to produce output to a file, especially in advanced scenarios involving large data handling. These classes are:
Using the StreamWriter class in C# to send output to a file is straightforward. The following example shows how you can use it.
# Get the directories in C:\ $Dirs = Get-ChildItem -Path C:\ -Directory # Open a stream writer $File = 'C:\Temp\Dirs.txt' $Stream = [System.IO.StreamWriter]::new($File) # Write the folder names for these folders to the file foreach($Dir in $Dirs) { $Stream.WriteLine($Dir.FullName) } # Close the stream $Stream.Close()
This script performs the following steps to list directories on the C:\ drive and save their paths to a text file:
$Dirs = Get-ChildItem -Path C:\ -Directory
This line uses Get-ChildItem with the -Directory parameter to get only the directories (not files) in the C:\ drive. The result is stored in the $Dirs variable as a list of directory objects.
$File = 'C:\Temp\Dirs.txt' $Stream = [System.IO.StreamWriter]::new($File)
These lines set up a file path (C:\Temp\Dirs.txt) where the directory list will be saved and then initialize a StreamWriter object to write to that file. This object is assigned to $Stream.
foreach($Dir in $Dirs) { $Stream.WriteLine($Dir.FullName) }
This loop goes through each directory object in $Dirs. For each directory, it writes the full path ($Dir.FullName) to the file using $Stream.WriteLine.
$Stream.Close()
After writing all directory paths, the script closes the StreamWriter.
You should set the correct line width with the -Width parameter in PowerShell to prevent truncation of long lines and ensure that file outputs are formatted as intended.
The -Width parameter in the Out-File cmdlet controls the maximum number of characters per line in the output. By default, it’s set to 80 characters, which may truncate longer lines. You can, for example, increase width to 200 characters, as shown below:
Get-Process | Out-File -FilePath "output.txt" -Width 200
Consider the following:
The default encoding PowerShell uses varies, depending on the cmdlet and the PowerShell version you are using. The following table shows the default encoding used:
Cmdlet / Operator | PowerShell 5.1 (and earlier) Default Encoding | PowerShell Core / PowerShell 7+ Default Encoding |
Out-File, Set-Content, Add-Content | UTF-16LE (Unicode) | UTF-8 (No BOM) |
>, >> (Redirection) | ASCII | UTF-8 (No BOM) |
UTF-8 encoding is recommended for cross-system compatibility. For legacy systems, however, you may want to specify -Encoding ASCII or -Encoding Unicode.
$PSDefaultParameterValues in PowerShell enables you to set default values for parameters across scripts and sessions, offering a way to enforce consistency without specifying options repeatedly.
Here is how you can set a global default for Out-File to use UTF8 encoding and wider width.
$PSDefaultParameterValues["Out-File:Encoding"] = "UTF8"
$PSDefaultParameterValues["Out-File:Width"] = 200
Combining the Out-File cmdlet with Format-Table or Format-List is a great way to produce well-structured, readable text output files.
Format-Table is best for data with a clear, row-and-column structure. It creates an organized, easy to read table-like format. However, to use it with the Out-File cmdlet, consider the following:
Here is an example:
Get-Process | Format-Table -Property Name, ID, CPU, WS -AutoSize | Out-File -FilePath "ProcessList.txt" -Width 200
Format-List displays data vertically, with one property per line. Use it when you have many properties or fields with lengthy values, so as to avoid truncation of such values. This format is suitable for reports and detailed logs.
Here is an example of using Format-List with Out-File:
Get-Process | Format-List -Property Name, ID, CPU, StartTime | Out-File -FilePath "DetailedProcessList.txt"
As with Format-Table, select only the properties you need.
It is always wise to check if a file exists before you attempt to write to it. This way, you can avoid accidental overwrites and decide what to do when a file already exists. The Test-Path cmdlet in PowerShell enables you to check for the existence of a file.
Following are the steps you should follow:
The Out-File cmdlet in PowerShell can sometimes lead to common pitfalls, especially around file handling, encoding, and appending content. Some common issues and their solutions are discussed below.
By default, the Out-File cmdlet overwrites the content of an existing file without warning, if a file with the same name already exists. Some ways to avoid this are:
By default, Out-File uses Unicode encoding in PowerShell 5.1 and earlier versions. It uses UTF-8 encoding in PowerShell Core and later versions.
The default encoding may not be compatible with your system or applications that expect a different encoding. Therefore, you should specify the encoding explicitly using the -Encoding parameter.
In constrained environments like PowerShell ISE, running scripts with the Out-File cmdlet may lead to issues such as:
To manage long output, you can:
Sometimes, a file is in use or locked by another process. In this case, the Out-File cmdlet will throw an error as it will not be able to write to it. You can handle this and other errors with a try/catch block. An example is as follows:
$content = "Write content to file" $filePath = "C:\Temp\Errors.txt" try { $content | Out-File -FilePath $filePath Write-Host "File written successfully." } catch { Write-Host "File is in use or locked by another process." }
By default, the Out-File cmdlet overwrites an existing file if one by the same name exists at the specified path. To avoid overwriting, you cam append output to the existing file. For that, use the >> operator or the Out-File cmdlet with the -Append parameter.
To get a list of processes and append the output to the processes.txt file, you can use:
Get-Process >> "C:\Temp\processes.txt"
Or
Get-Process | Out-File -FilePath "C:\Temp\processes.txt" -Append
Use the -NoClobber parameter with the Out-File cmdlet to prevent overwrites. See the Manage Overwrites section for details.
Both the Out-File and Set-Content cmdlets in PowerShell write content to a file, but they differ in functionality.
The following table sums up the differences:
Feature | Out-File | Set-Content |
Default Action | Overwrites (can use -Append to append) | Overwrites (use Add-Content to append) |
Formatting | Retains console-like formatting | Plain text, no formatting |
Encoding | Yes | Yes |
Using PowerShell, you can export just the error messages to a log file. The 2> redirection operator is used to redirect the error stream to a file.
Example 1:
Here is how you can run a command and redirect error messages to a log file.
2> C:\Temp\error_log.txt
Example 2:
This command will only log the error messages, if any, to C:\Temp\error_log.txt and ignore other outputs.
Get-Content "C:\NonExistentFile.txt" 2> C:\Temp\error_log.txt
See the Handling Specific Output Streams section for additional information.
The Export-Csv and ConvertTo-Json cmdlets enable you to write data to a CSV or JSON file.
To write data to a CSV file, do the following:
The following example shows sample data as an array of custom objects that will be written to a file.
$data = @( [pscustomobject]@{Name="Anne"; Age=40; Department="HR"}, [pscustomobject]@{Name="Leo"; Age=35; Department="IT"}, [pscustomobject]@{Name="Sarah"; Age=28; Department="Finance"} ) $data | Export-Csv -Path "C:\Temp\data.csv" -NoTypeInformation
To write data to a JSON file, do the following:
The following example shows sample data as an array of custom objects that will be converted to JSON format and saved to a file.
$data = @( [pscustomobject]@{Name="Anne"; Age=40; Department="HR"}, [pscustomobject]@{Name="Leo"; Age=35; Department="IT"}, [pscustomobject]@{Name="Sarah"; Age=28; Department="Finance"} ) $data | ConvertTo-Json | Out-File -FilePath "C:\Temp\data.json"