How to Write to a File in PowerShell: Simple Guide
In PowerShell, you can write to a file using the
Set-Content or Out-File cmdlets. For example, Set-Content -Path 'file.txt' -Value 'Hello' writes 'Hello' to the file named file.txt. These commands create the file if it doesn't exist or overwrite it if it does.Syntax
PowerShell provides several ways to write text to a file. The two most common commands are:
- Set-Content: Writes or replaces content in a file.
- Out-File: Sends output to a file, similar to redirecting output.
Basic syntax for Set-Content:
Set-Content -Path <filePath> -Value <text>
Basic syntax for Out-File:
<command> | Out-File -FilePath <filePath>
Both commands create the file if it does not exist and overwrite it by default.
powershell
Set-Content -Path 'example.txt' -Value 'Hello, World!' "Hello, World!" | Out-File -FilePath 'example.txt'
Example
This example shows how to write a simple text string to a file named greeting.txt using Set-Content. It then reads the file content to confirm the write operation.
powershell
Set-Content -Path 'greeting.txt' -Value 'Hello from PowerShell!' Get-Content -Path 'greeting.txt'
Output
Hello from PowerShell!
Common Pitfalls
Some common mistakes when writing to files in PowerShell include:
- Using
Set-Contentwhen you want to append text instead of overwrite. UseAdd-Contentto add text without deleting existing content. - Not specifying the full path, which may write the file to an unexpected folder.
- Forgetting that
Out-Fileuses Unicode encoding by default, which might cause issues with some applications expecting ASCII or UTF8.
powershell
## Wrong: Overwrites file when appending intended Set-Content -Path 'log.txt' -Value 'New entry' ## Right: Append text to existing file Add-Content -Path 'log.txt' -Value 'New entry'
Quick Reference
| Command | Purpose | Notes |
|---|---|---|
| Set-Content | Write or overwrite file content | Creates file if missing, overwrites existing content |
| Add-Content | Append text to file | Adds text without deleting existing content |
| Out-File | Send output to file | Supports encoding options, default is Unicode |
| Get-Content | Read file content | Useful to verify file contents |
Key Takeaways
Use Set-Content to write or overwrite file content simply.
Use Add-Content to append text without deleting existing data.
Out-File sends command output to a file and supports encoding options.
Always specify full file paths to avoid confusion about file location.
Verify file content with Get-Content after writing.