03 / FILES AND FORMATS · LESSON 10

Make your first file

Write a small checklist and read its lines back.

10 min · learn at your pace

Text goes in, text comes out

Set-Content writes text, replacing the previous content of a file. Add-Content appends new content. Get-Content reads it:

Set-Content './notes.txt' 'Check the backups'
Add-Content './notes.txt' 'Review the logs'
Get-Content './notes.txt'

By default, Get-Content returns a string for each line. With -Raw, it returns one string containing the entire file, including its line breaks.

Write a collection

$steps = @('Discover', 'Inspect', 'Automate')
$steps | Set-Content './steps.txt'

Each item becomes a line. Use -Encoding utf8 when you want an explicit text encoding. Binary data needs different handling; do not treat an arbitrary binary file as text.

Be deliberate about replacing files. In this lab you can reset the exercise to restore its starting state. On a real system, review your target path before using a command that overwrites content.

Try an example.ps1
Set-Content './notes.txt' 'Check the backups'
Add-Content './notes.txt' 'Review the logs'
Get-Content './notes.txt'
YOUR TURN

Put it into practice.

Create checklist.txt with three lines, in this order: Discover, Inspect, Automate. Then read the file and output its lines.

See an explained solution
One way to solve it.ps1
$steps = @('Discover', 'Inspect', 'Automate')
$steps | Set-Content './checklist.txt'
Get-Content './checklist.txt'

Set-Content writes one line per array item. Reading the file produces three strings in the original order.