Low Orbit Flux Logo 2 F

PowerShell How To Write To Text File

One task that is likely to come up when using PowerShell is writing text to a file. This is easy to do. There are multiple different methods to achieve this same goal. The hard part is choosing which method to use.

This is the easy way to write to a text file with powershell. It will overwrite the file if it exists.


"My text to write out" > E:\data\output.txt

This will write to a file. The file will be overwritten. The string specified is piped to the Out-File cmdlet which will write to the file specified.


"My text to write out" | Out-File -FilePath E:\data\output.txt

This will append to a file. It just adds to the end of the file without overwriting. The difference between this and the above example is that here we specified Append.


"My text to write out" | Out-File -FilePath E:\data\output.txt -Append

You can pipe the output of a command to a file like this.


Get-Process | Out-File -FilePath E:\data\output.txt

Verify - You can read the file to verify that it has been written as expected. Use this command to read it.


Get-Content E:\data\output.txt

Write a Text File with PowerShell - Additional Methods

You can also use Set-Content and Add-content to write files.

The following will append to a file:


Add-Content -Path E:\data\output.txt -Value "My text to write out"

This will overwrite a file.


Set-Content -Path E:\data\output.txt -Value "My text to write out"

Use PassThru to show output in addition to writing it to the file:


Add-Content -Path E:\data\output.txt -Value "My text to write out" -PassThru
Set-Content -Path E:\data\output.txt -Value "My text to write out" -PassThru

A list of items can be written to a new line each:


"apple", "orange" | Out-File E:\data\output.txt

List of items all written to the same line:


"apple", "orange" | Out-File E:\data\output.txt -NoNewline

You can output using variables like this:


$a = Get-Process
Add-Content -Path E:\data\a1.txt -Value $a

$b = "test 123"
Add-Content -Path E:\data\b1.txt -Value $b