PowerShell is all about objects. In most cases, you display the output on the screen or store them in a variable. But in some instances, redirecting the output to a text file makes more sense, like when exporting information or writing a log file.
PowerShell has a cmdlet called Out-File that lets you redirect output to a text file. If you’re familiar with the > and >> redirectors in most terminal shells, then Out-File would not be too much of a stranger to you.
In this blog, we’ll explore how to use the Out-File cmdlet, its different parameters, and some examples to help you get started.
Table of Contents
The PowerShell Out-File Syntax
Let’s first familiarize ourselves with the Out-File syntax. To display its syntax, run the below command in PowerShell.
Get-Command Out-File -Syntax
The basic syntax of the Out-File cmdlet is as follows:
As you can see, Out-File has two sets of parameters. The only difference is you cannot use both the FilePath and LiteralPath parameters in one command. Below are the explanation of each parameter for better understanding.
- FilePath (required): Specifies the path and file name of the file to which the output is sent. Wildcards are allowed in the path. The target file is created if it does not exist.
- LiteralPath (required): Specifies the literal path and file name of the file to which the output is sent. Wildcards are not allowed in the path, but expressions/variables are. The target file is created if it does not exist.
- InputObject (optional): Specifies the object that is being sent to the file. This can be a variable, a command, or a script block.
- Append (optional): Appends the output to the end of an existing file. If the file doesn’t exist, a new file is created. This parameter
- Encoding (optional): Specifies the character encoding used in the output file. The default unicode on Windows PowerShell and utf8NoBom on PowerShell 7+.
- NoClobber (optional): Prevents the cmdlet from overwriting an existing file.
- Force (optional): Allows the cmdlet to overwrite read-only files.
- WhatIf (optional): Shows what would happen if the cmdlet runs.
- Confirm (optional): Prompts you for confirmation before running the cmdlet.
PowerShell Redirect Output to File Examples
Here are some Out-File examples to help you get started.
Note. Learn how to use PowerShell function Return.
Example 1: PowerShell Pipe Output to File
The most common usage of Out-File is piping an object to it. For example, let’s run the Get-Process command to list all running processes and pipe the result to the Out-File command. The below command creates the file process.txt on the current directory.
Get-Process | Out-File -FilePath .\process.txt
To display the file’s content, run the Get-Content command below.
Get-Content -Path .\process.txt
Example 2: Force to Overwrite Read-Only Files
By default, Out-File will overwrite a file if it already exists. But not if the file is read-only.
Suppose we have a read-only file called services.txt.
If we try to use Out-File to overwrite it, it will fail. For example, the below command gets all the services using the Get-Service command and lets PowerShell redirect all output to file.
Get-Service | Out-File -FilePath .\services.txt
As you can see below, the Out-File command failed.
To force Out-File to overwrite this file, append the -Force switch.
Get-Service | Out-File -FilePath .\services.txt -Force
The result below shows that Out-File was able to write over the read-only file.
But did you notice the error above with Get-Service? Why did it not get written to the output file? That’s because Out-File only accepts input from the Output stream. It ignores the Error, Warning, Verbose, and Debug streams.
Example 3: Append PowerShell Output to File in a New Line
Sometimes, you’d want Out-File to append items to the existing file rather than overwriting it. This is especially useful when creating logs or tracking changes.
To append the output to an existing file, you can use the -Append switch. The below example will append each fruit name in the array to the fruits.txt file:
"Apple;", "Banana;", "Orange;", "Avocado;" | ForEach-Object { Out-File -InputObject $PSItem ` -FilePath .\fruits.txt ` -Append } Get-Content -Path .\fruits.txt "Mango;" | Out-File -FilePath .\fruits.txt -Append Get-Content -Path .\fruits.txt
- The first command wrote each fruit name (“Apple;”, “Banana;”, “Orange;”, “Avocado;”) to a new line in fruits.txt.
- The second command displayed the file’s content on the screen.
- The third command appended another fruit name (“Mango;”) to the same file in a new line.
- The fourth command displays the same file’s content showing the appended item.
Example 4: Append PowerShell Output to File in the Same Line
The default behavior when appending output to the file is to add a new line. If needed, you can also append the new output to the end of the line instead of creating a new line. This can be done by using the -NoNewLine switch.
"Apple;", "Banana;", "Orange;", "Avocado;" | ForEach-Object { Out-File -InputObject $PSItem ` -FilePath .\fruits.txt ` -Append -NoNewline } Get-Content -Path .\fruits.txt "Mango;" | Out-File -FilePath .\fruits.txt -Append -NoNewline Get-Content -Path .\fruits.txt
Example 5: PowerShell Script Output to File
When you write a PowerShell script, adding a logging functionality is a great way to keep track of your output. It may also help with debugging your script if there are issues along the way.
In this example, we’ll add a function that writes output to a log file with different categories.
Function Say { [CmdletBinding()] param ( [Parameter()] [ValidateSet( 'SUCCESS', 'FAIL', 'WARNING', 'ERROR', 'INFORMATION' )] [String] $LogItemType = 'SUCCESS' , [Parameter(Mandatory)] [String] $Message , [Parameter(Mandatory)] [String] $LogFileName ) # Compose the log message $LogMessage = "$(Get-Date -Format "yyyy-MM-dd hh:mm:sstt (zzzz)"): [$($LogItemType)] $($Message)" # Display the log message on screen $LogMessage # Output the log message to file $LogMessage | Out-File -Append -FilePath $LogFileName -Force }
To use this function, you must specify the following parameters.
- LogFileName — This is the full path to the log file.
- LogItemType — Specify the log item type. The valid values are:
- SUCCESS
- FAIL
- WARNING
- ERROR
- INFORMATION
- Message — The log item message.
$LogFileName = ".\log.txt" Say -LogItemType WARNING ` -Message "This is a warning message" ` -LogFileName $LogFileName
And if you check the log file, it contains the log item you sent.
Best Practices
Here are some best practices to keep in mind when using the Out-File cmdlet:
Use Meaningful File Names
When creating files with the Out-File cmdlet, make sure to use meaningful file names that describe the contents of the file. Doing so can make it easier to find and manage files later.
Use Consistent Encoding
One of the most common issues is file encoding. If you’re sending output to a file that requires a specific encoding, make sure to specify the encoding using the -Encoding parameter. If you don’t specify an encoding, the default encoding will be used, which may not be compatible with your file.
Make Sure You Have the Correct Permissions
If you’re trying to write to a file and you get a “permission denied” error, ensure you have permission to write to the file. You may need to run PowerShell as an administrator or change the permissions on the file.
Correct Output File Path
Make sure to double-check the file path before running the Out-File cmdlet. Only the output file can be created automatically; but if you specify an invalid path or the path (directory) does not exist, the command will fail.
Accidental Overwrite
Additionally, the Out-File command will overwrite the file if it already exists. A good way to avoid accidentally overwriting a file is to add logic to test if the file already exists.
if (Test-Path $filename) { Write-Host "$filename already exists." } else { Out-File $filename }
Or you can also append the -NoClobber switch.
Test Your Scripts
Before running your PowerShell scripts in a production environment, make sure to test them in a development or testing environment. This can help you catch any issues with your scripts before they cause problems in production.
Conclusion
The Out-File cmdlet is a powerful tool for sending PowerShell output to a file. By understanding its different parameters, common issues, use cases, and best practices, you can use this cmdlet to create and manage files in your PowerShell scripts. Happy scripting!