Reading and Writing Text Files
Prerequisites: Navigating and managing files
Writing
Set-Content -Path notes.txt -Value 'first line'
Add-Content -Path notes.txt -Value 'second line', 'third line'
'fourth line' | Out-File -FilePath notes.txt -Append
Get-Content notes.txt
first line
second line
third line
fourth line
Set-Content— creates or overwrites a file.Add-Content— appends.Out-File— writes output as it would look on screen (tables and all). UseSet-Contentfor plain values,Export-CsvorConvertTo-Jsonfor data.- The
>and>>redirection operators work too, likeOut-File.
Reading
1..5 | ForEach-Object { "line $_" } | Set-Content data.txt
$lines = Get-Content data.txt
$lines.Count
$lines[1]
Get-Content data.txt -TotalCount 2
Get-Content data.txt -Tail 1
(Get-Content data.txt -Raw).Length
5
line 2
line 1
line 2
line 5
40
Get-Contentreturns an array of lines.-TotalCount/-Tailread the first or last lines (-Tailwith-Waitfollows a growing log, liketail -f).-Rawreturns the whole file as one string — needed for multi-line regex or JSON.
Processing line by line
Set-Content app.log @'
2025-04-22 INFO Server started
2025-04-22 ERROR Database timeout
2025-04-22 INFO Request served
2025-04-22 ERROR Disk almost full
'@
Get-Content app.log | Where-Object { $_ -match 'ERROR' } | ForEach-Object { ($_ -split '\s+', 3)[2] }
Database timeout
Disk almost full
Piping Get-Content streams one line at a time, so even huge files don't
have to fit in memory.
Encoding
PowerShell 7 reads and writes UTF-8 without a BOM by default. Windows
PowerShell 5.1 used different defaults per cmdlet (often UTF-16 for
Out-File), a classic source of garbled files. When a file must be read by
another program, be explicit: -Encoding utf8.
Common mistakes
- Editing a file in a pipeline that reads it:
Get-Content f.txt | ... | Set-Content f.txtcan empty the file. Wrap the read in parentheses so it finishes first:(Get-Content f.txt) | ... | Set-Content f.txt.