Netwrix Corporation

11/21/2024 | News release | Distributed by Public on 11/21/2024 12:01

PowerShell Write to File: 'Out-File' and File Output Techniques

Introduction to Outputting in PowerShell

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.

  • Commands may return a large amount of data that is difficult to handle in real time. You can redirect or save this data to process or review it at your convenience.
  • To use the results of a command in another process or script, you can use the PowerShell output to file command to save the output to a file or variable for easy reuse.
  • Scheduled jobs or other automated tasks usually often run in the background. You may not be able to see the output in real time, so saving it allows you to review it later.
  • Sometimes, the output may contain more information than you need. You can, therefore, redirect or save it to filter and format it.
  • When you run commands on remote systems, you may not have access to the console to view real-time output. Saving or redirecting provides you with a record of what happened on the remote system.
  • Organizations generate reports based on system states, configurations, or performance metrics. Using PowerShell, they can query system data, generate reports and output them to a file for future review.
  • PowerShell can be used to gather hardware and software inventory information for asset management and compliance. This data can then be output to a file for greater visibility and simplified management.
  • When automating tasks, it is essential to track the actions taken and the results. Redirecting output to a file helps create logs for auditing.
  • If a script fails, you need to know the root cause. By saving the output, you can review it later for error handling, debugging and troubleshooting.

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.

Core Methods for Outputting PowerShell Results to Files

The Out-File Cmdlet

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.

Out-File Syntax

Here’s the basic syntax for the Out-File cmdlet:

Out-File

   [-FilePath] 

   [[-Encoding] ]

   [-Append]

   [-Force]

   [-NoClobber]

   [-Width ]

   [-NoNewline]

   [-InputObject ]

   [-WhatIf]

   [-Confirm]

   []

Parameters

The PowerShell Out-File cmdlet accepts the following parameters:

ParameterDescription
-FilepathSets 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.
-AppendAdds output to the end of the file without overwriting existing content
-ForceOverrides read-only attribute and overwrites an existing read-only file. This parameter does not override security restrictions.
-NoClobberPrevents overwriting an existing file. By default, if a file exists in the specified path, the Out-File cmdlet overwrites the file without warning.
-WidthLimits the number of characters on each line in the output file (default 80). Any additional characters are truncated, not wrapped.
-NoNewLineSpecifies 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.
-InputObjectSpecifies 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.
-WhatIfRuns the cmdlet in test mode to show the expected results of the cmdlet
-ConfirmPrompts for confirmation before running the cmdlet

Use Cases

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.

Append Out-File to a PowerShell cmdlet

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.

Append Out-File to a text string

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.

Append Out-File to a Variable

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 >>)

Redirection Operators (> and >>) in PowerShell are a simple and quick alternative to the Out-File cmdlet, enabling you to redirect output to a file.

  • The > operator is equivalent to the Out-File cmdlet with no extra parameters. It overwrites the file if it exists, or creates a new one if it does not.
  • The >> operator is equivalent to Out-File -Append. It appends the output to the file if it exists, or creates a new one if it does not exist.

These operators also have other uses like redirecting error or verbose output streams, which is beyond the scope of this article.

Basic syntax

The basic syntax for using the operators is as follows:

 >      # Overwrites
 >>     # Appends

Notice that the redirect operators do not use any parameters.

Example 1 – Using the > Operator

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

Example 2 – Using the >> Operator

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.

Out-File Cmdlet versus Redirection Operators (> and >>)

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.

FeatureOut-File CmdletRedirection Operators (> and >>)
ParametersAccepts parametersDoes not accept parameters
Overwriting BehaviorDefault is overwrite; uses -Append for appending and -NoClobber to avoid overwriting> overwrites, >> appends No built-in control to prevent overwriting
Encoding ControlAllows specifying encoding with -EncodingLimited encoding control (UTF-8 in PowerShell 6+, Unicode in older versions)
Width ControlSupports setting line width with -WidthNo control over line width
Error HandlingOnly successful results are exported, so warnings or errors are not written to the fileCan specify which stream you want to export, like success, error, warning, etc.
Usage in ScriptsBest for scripts that require more control over outputQuick and convenient for simple redirection

When to Use Each

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.

When to use the Out-File cmdlet

  • For specific encoding (e.g., ASCII, UTF8, Unicode)
  • To avoid overwriting files (using -NoClobber)
  • For control over the line width of output (using -Width)
  • In append mode while maintaining other output control options

When to use > and >>

  • When you want quick redirection for output without additional formatting or encoding
  • When overwriting (>) or appending (>>) the existing file is desired

Advanced File Output Techniques

Manage Overwrites

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:

  • Add (append) the output to the existing file
  • Prevent overwrite, with the result that the existing file will not be overwritten and the output will not be saved to file

Append Output

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

Prevent Overwrite

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

Force Overwrite

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

Output Formatting and Encoding

PowerShell’s Out-File cmdlet provides options to customize output formatting and encoding.

Format Output

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.

Example 1 Set the Width

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

Example 2 Format with Format-Table

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

Set Encoding

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:

  • UTF8 – Common for web applications, supports all characters.
  • ASCII – Limited to basic English characters, compact but restrictive.
  • Unicode (UTF-16) – Good for Windows compatibility, can handle a wide range of special characters, symbols, and international text, but uses more space.
  • Default – Uses the system’s default encoding, which might vary and can be unpredictable across platforms.

Example 1 — Use UTF-8 Encoding

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

Example 2 — Use ASCII Encoding

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

Handling Specific Output Streams

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.

OperatorDescription / StreamWrite cmdlet
> Success onlyWrite-Output
2>Error onlyWrite-Error
3>Warning onlyWrite-Warning
4>Verbose onlyWrite-Verbose
5>Debug onlyWrite-Debug
6>Information onlyWrite-Information
*>All

Example 1 — Send error messages to file

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

Example 2 — Send Warnings to file

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

Alternative Methods for Output

Set-Content and Add-Content Cmdlets

The Set-Content and Add-Content cmdlets are another way to write output to file.

  • Set-Content overwrites existing content in the file with the new content provided. If the file does not exist, it creates it.
  • Add-Content appends new content to the end of the existing file content. If the file does not exist, it will create it, but it will not replace existing content.

The Set-Content cmdlet

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"

The Add-Content cmdlet

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.

Example 1 — Append text to a file

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.

Example 2 — Append text to multiple files

To add the same content to multiple files, you have several options.

  • Use wildcards in the path to specify the files you want to update
  • Exclude files names that you do not want to update

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*"

Example 3 — Add multiple lines of text

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

.Net Classes

You can use .NET classes to produce output to a file, especially in advanced scenarios involving large data handling. These classes are:

  • BinaryWriter – Writes primitive data types in binary form to a stream.
  • StreamWriter – Used for writing characters to a stream in a specific encoding. Often used for creating or modifying text files.
  • StringWriter – writes information to a string. With this class, PowerShell stores the string information in a StringBuilder object.

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:

Step 1:

$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.

Step 2:

$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.

Step 3:

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.

Step 4:

$Stream.Close()

After writing all directory paths, the script closes the StreamWriter.

Best Practices for PowerShell File Output

Set the correct line width to avoid truncation

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:

  • To avoid unnecessary white space or truncation, set a -Width to match the longest line. For most outputs, a width of 120–200 characters should work well.
  • For data with many columns (like a CSV file), set a larger width to accommodate the full line.
  • In a pipeline, use Out-String -Width to control line width, ensuring the entire line fits within the specified width before piping to Out-File.

Set the right encoding

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 / OperatorPowerShell 5.1 (and earlier) Default EncodingPowerShell Core / PowerShell 7+ Default Encoding
Out-File, Set-Content, Add-ContentUTF-16LE (Unicode)UTF-8 (No BOM)
>, >> (Redirection)ASCIIUTF-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.

Use $PSDefaultParameterValues to set defaults across scripts

$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

Combine Out-File with Format-Table and Format-List for better structured output

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

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:

  • Use the -Property parameter to specify only the columns you need. This will prevent clutter in the output file.
  • Use the -AutoSize parameter to optimize column width to fit the content. This will reduce extra whitespace or truncation.
  • Use the -Width parameter to prevent truncation and keep the output aligned.

Here is an example:

Get-Process | Format-Table -Property Name, ID, CPU, WS -AutoSize | Out-File -FilePath "ProcessList.txt" -Width 200

Format-List

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.

Prevent file conflicts with Test-Path to verify if files exist before writing

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:

  1. Assign the file path to a variable.
  2. Use the Test-Path cmdlet to check if the file exists.
  3. Decide on whether you want to append, overwrite, rename, or skip writing.
  4. Use the Out-File cmdlet to create or write to the file.

Common Pitfalls and Solutions

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.

Avoid data loss through overwriting

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:

  • Add the output to the existing file rather than overwrite it using the -Append parameter.
  • Check if the file exists with Test-Path and decide how you want to proceed with Out-File.

Avoid data loss through improper encoding

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.

Manage output in long-running scripts to ensure performance

In constrained environments like PowerShell ISE, running scripts with the Out-File cmdlet may lead to issues such as:

  • Failure to handle complex data structures as expected
  • Truncation of lengthy output

To manage long output, you can:

  • Use the -Width parameter to set a suitable width
  • Export complex data to structured formats like CSV or JSON using the Export-Csv or ConvertTo-Json cmdlets

Handle logging and error handling in PowerShell scripts

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."

}

FAQs

How do I append output to a file in PowerShell?

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

How do I prevent overwriting a file?

Use the -NoClobber parameter with the Out-File cmdlet to prevent overwrites. See the Manage Overwrites section for details.

What’s the difference between Out-File and Set-Content?

Both the Out-File and Set-Content cmdlets in PowerShell write content to a file, but they differ in functionality.

  • Out-File formats and outputs the data exactly as it is displayed in the console. It can work with pipelines and can handle complex formatting, like tables or detailed command results.
  • Set-Content writes the data as plain text, without any formatting.

The following table sums up the differences:

FeatureOut-FileSet-Content
Default ActionOverwrites (can use -Append to append)Overwrites (use Add-Content to append)
FormattingRetains console-like formattingPlain text, no formatting
EncodingYesYes

Can I export just the error messages to a log file?

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.

How do I write data to a CSV or JSON file?

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:

  1. Prepare your data in a format like an array of objects or a PowerShell custom object.
  2. Use Export-Csv to write it to a file.

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:

  1. Prepare your data in a format like an array of objects or a PowerShell custom object.
  2. Use ConvertTo-Json to convert the data into JSON format.
  3. Pipe the JSON output to Out-File.

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"
Since 2012, Jonathan Blackwell, an engineer and innovator, has provided engineering leadership that has put Netwrix GroupID at the forefront of group and user management for Active Directory and Azure AD environments. His experience in development, marketing, and sales allows Jonathan to fully understand the Identity market and how buyers think.