DEV Community

Cover image for PowerShell Set-Content vs Add-Content: The Real Difference (and Why Your Log Only Has the Last Line)
arnostorg
arnostorg

Posted on Edited on

PowerShell Set-Content vs Add-Content: The Real Difference (and Why Your Log Only Has the Last Line)

Your script checks three servers and writes a line for each one to a log. You open the log afterwards and there is exactly one line in it: the last server. No error, no warning. The loop ran three times, and the log only remembers one of them.

The cause is one word: you used Set-Content where you needed Add-Content. This tip shows the real difference between the two, the stale-file trap that catches even people who know the difference, and a log pattern that gives you a clean file on every run.

The one-line difference

  • Set-Content replaces everything in the file with what you give it. If the file does not exist, it creates it.
  • Add-Content appends to the end of the file. If the file does not exist, it creates it too.

That's it. Both write text, both default to UTF-8 without a BOM in PowerShell 7, and both take input from -Value or the pipeline. The difference only shows up when you write more than once.

The bug: Set-Content in a loop

foreach ($s in 'web01','web02','db01') {
    "checked $s" | Set-Content -Path .\run.log
}
Get-Content -Path .\run.log
Enter fullscreen mode Exit fullscreen mode

Output:

checked db01
Enter fullscreen mode Exit fullscreen mode

Every pass through the loop overwrote the file. The first two lines were written, then wiped. Swap in Add-Content:

foreach ($s in 'web01','web02','db01') {
    "checked $s" | Add-Content -Path .\run2.log
}
Get-Content -Path .\run2.log
Enter fullscreen mode Exit fullscreen mode

Output:

checked web01
checked web02
checked db01
Enter fullscreen mode Exit fullscreen mode

All three lines are there.

The opposite bug: Add-Content never forgets

Run that Add-Content loop a second time and count the lines:

foreach ($s in 'web01','web02','db01') {
    "checked $s" | Add-Content -Path .\run2.log
}
(Get-Content -Path .\run2.log).Count
Enter fullscreen mode Exit fullscreen mode

Output:

6
Enter fullscreen mode Exit fullscreen mode

Add-Content keeps everything from earlier runs. For a long-running log that is what you want. For a "results of this run" file, it means yesterday's results look like today's.

The log pattern: Set-Content once, then Add-Content

Start the run with Set-Content to reset the file, then append everything after it:

$log = '.\deploy.log'
Set-Content -Path $log -Value "Deploy started $(Get-Date -Format 'yyyy-MM-dd HH:mm')"

foreach ($s in 'web01','web02') {
    Add-Content -Path $log -Value "deployed $s"
}

Add-Content -Path $log -Value 'Deploy finished'
(Get-Content -Path $log).Count
Enter fullscreen mode Exit fullscreen mode

Output:

4
Enter fullscreen mode Exit fullscreen mode

Four lines every time: the header, two servers, the footer. Run it again and it is still four.

The stale-file trap: Set-Content with nothing to write

This one surprised me while testing. Say yesterday's run found a failure and wrote it to failed.txt. Today everything passes, so your filter returns nothing:

'web01 FAILED' | Set-Content -Path .\failed.txt

$failed = 'web01 OK','web02 OK' | Where-Object { $_ -like '*FAILED*' }
$failed | Set-Content -Path .\failed.txt
Get-Content -Path .\failed.txt
Enter fullscreen mode Exit fullscreen mode

Output:

web01 FAILED
Enter fullscreen mode Exit fullscreen mode

The file still says web01 failed. When nothing comes down the pipeline, Set-Content never runs its write, so the old content stays. (In my test it did not even create the file when it was missing.) Anyone reading failed.txt sees yesterday's failure as today's.

Pass the variable with -Value instead of piping it:

Set-Content -Path .\failed.txt -Value $failed
(Get-Item -Path .\failed.txt).Length
Enter fullscreen mode Exit fullscreen mode

Output:

0
Enter fullscreen mode Exit fullscreen mode

With -Value the cmdlet runs even when $failed is empty, so the file is emptied. Use -Value for any "current state" file that is allowed to be empty.

Two Add-Content gotchas

It glues onto a last line that has no newline. Add-Content writes at the very end of the file. If the file was written with -NoNewline (or by a tool that skips the final line break), your new text lands on the same line:

Set-Content -Path .\a.txt -Value 'first' -NoNewline
Add-Content -Path .\a.txt -Value 'second'
Get-Content -Path .\a.txt
Enter fullscreen mode Exit fullscreen mode

Output:

firstsecond
Enter fullscreen mode Exit fullscreen mode

It creates the file, not the folder. Add-Content -Path .\logs\today.log fails with "Could not find a part of the path" when logs does not exist. Create the folder once at the top of the script:

New-Item -ItemType Directory -Path .\logs -Force | Out-Null
Add-Content -Path .\logs\today.log -Value 'run started'
Enter fullscreen mode Exit fullscreen mode

When you have many lines: write once

Each Add-Content call opens the file, writes and closes it again. For a handful of lines that doesn't matter. For thousands it does. Collect the lines, then write them in one go:

$lines = foreach ($s in 'web01','web02','db01') { "checked $s" }
$lines | Set-Content -Path .\run3.log
Get-Content -Path .\run3.log
Enter fullscreen mode Exit fullscreen mode

Output:

checked web01
checked web02
checked db01
Enter fullscreen mode Exit fullscreen mode

In my test, 2,000 separate Add-Content calls took about 315 ms, while piping the same 2,000 lines into one Set-Content took about 23 ms. Both files ended up with 2,000 lines. Your numbers will differ, but the ratio is the point.

Preview before you overwrite: -WhatIf

Set-Content is destructive, so it supports -WhatIf:

Set-Content -Path .\run3.log -Value 'x' -WhatIf
Enter fullscreen mode Exit fullscreen mode

Output:

What if: Performing the operation "Set Content" on target "Path: C:\Work\run3.log".
Enter fullscreen mode Exit fullscreen mode

Nothing was written.

Quick reference

You want Use
Replace the whole file Set-Content -Path $file -Value $text
Add a line to the end Add-Content -Path $file -Value $line
A fresh log on every run Set-Content for the first line, Add-Content after it
A file that may need to become empty Set-Content -Path $file -Value $result (not `$result \
Thousands of lines Collect them, then pipe once into {% raw %}Set-Content
To check first Add -WhatIf

I tested every block above in PowerShell 7.4.6. The demo ran on Linux, so the -WhatIf path above is shown as it would look on Windows; the behavior is the same. Docs: Set-Content on Microsoft Learn, Add-Content on Microsoft Learn, and about_Character_Encoding.

Related tips: Set-Content basics for writing text to files, Add-Content basics for appending text, Out-File vs Set-Content and why encoding matters, and tailing the last lines of a log with Get-Content.

Practice it hands-on

Overwrite-versus-append mistakes stick once you have made them yourself. CMD Master's free interactive PowerShell, CMD and Bash terminal lessons run in your browser, so you can practice writing and appending to files without touching a real log.

Your turn: what does this output?

What does the last line print?

Set-Content -Path .\q.txt -Value 'a','b'
Add-Content -Path .\q.txt -Value 'c'
Set-Content -Path .\q.txt -Value 'd'
Add-Content -Path .\q.txt -Value 'e','f'
(Get-Content -Path .\q.txt) -join ','
Enter fullscreen mode Exit fullscreen mode

Drop your answer in the comments before you run it. I'll reply with the answer and why.

Top comments (0)