Skip to content
AgileLogics
5 min read

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). Use Set-Content for plain values, Export-Csv or ConvertTo-Json for data.
  • The > and >> redirection operators work too, like Out-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-Content returns an array of lines.
  • -TotalCount / -Tail read the first or last lines (-Tail with -Wait follows a growing log, like tail -f).
  • -Raw returns 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.txt can empty the file. Wrap the read in parentheses so it finishes first: (Get-Content f.txt) | ... | Set-Content f.txt.