0
0
PowerShellscripting~5 mins

Writing files (Set-Content, Out-File) in PowerShell

Choose your learning style9 modes available
Introduction

Writing files lets you save information from your script to your computer. This helps keep data for later use or sharing.

Save a list of names or data from a script to a text file.
Create a log file to track what your script does.
Export results from a command to share with others.
Save configuration settings from a script.
Write output from a script to a file for backup.
Syntax
PowerShell
Set-Content -Path <file-path> -Value <content>
Out-File -FilePath <file-path> [-Encoding <encoding>] [-Append]

Set-Content replaces the file content or creates a new file.

Out-File sends output to a file and can append or overwrite.

Examples
This writes "Hello World" to example.txt, replacing any existing content.
PowerShell
Set-Content -Path "C:\temp\example.txt" -Value "Hello World"
This writes "Hello again" to example.txt with UTF8 encoding.
PowerShell
Out-File -FilePath "C:\temp\example.txt" -InputObject "Hello again" -Encoding UTF8
This adds "More text" to the end of example.txt without removing existing content.
PowerShell
Out-File -FilePath "C:\temp\example.txt" -InputObject "More text" -Append
Sample Program

This script writes "First line" to output.txt, then adds "Second line" below it. Finally, it reads and shows the file content.

PowerShell
Set-Content -Path "output.txt" -Value "First line"
Out-File -FilePath "output.txt" -InputObject "Second line" -Append
Get-Content -Path "output.txt"
OutputSuccess
Important Notes

Use Set-Content when you want to replace the whole file content.

Use Out-File with -Append to add to existing files.

Check file paths carefully to avoid overwriting important files.

Summary

Set-Content writes or replaces file content.

Out-File sends output to a file and can append.

Use these commands to save script results or logs easily.