PoshBytes: Add-Content vs Out-File

PoshBytes: Add-Content vs Out-File

Today, we’re tackling two cmdlets that both claim to “write to a file” but behave like distant cousins at a family reunion. That’s right, it’s Add-Content vs Out-File.

This post is a companion for the video embedded below. Scroll down to see the code from the video.

Step 1: Behold the Data

Let’s start with some gloriously structured output:

$PSVersionTable

This command outputs a tidy table showing your PowerShell version info. But what happens when we try to save this data to a file?

Step 2: Writing to Files — The First Attempt

$PSVersionTable | Out-File -FilePath .\OutFile.txt
$PSVersionTable | Add-Content -Path .\AddContent.txt

Both commands create a file, but not in the same way. Out-File preserves the formatting like a PowerShell butler with a clipboard. Add-Content just shoves raw objects into the file like it’s late for a meeting.

Step 3: The Results

Get-Content -Path .\OutFile.txt
Get-Content -Path .\AddContent.txt

Out-File looks lovely. Add-Content… not so much. It needs strings to behave properly.

Step 4: Fixing Add-Content with Out-String

$PSVersionTable | Out-String | Add-Content -Path .\AddContent.txt

Adding Out-String translates the data into something Add-Content can digest. Now it stops throwing object references around like confetti.

Step 5: Overwriting vs Appending

$PSVersionTable | Out-File -FilePath .\OutFile.txt
$PSVersionTable | Out-File -FilePath .\OutFile.txt -Append

By default, Out-File overwrites the existing content like it’s rebooting history. Add -Append to let the past and present coexist peacefully in the same file.

Step 6: Use NoClobber to Protect Files

$PSVersionTable | Out-File -FilePath .\OutFile.txt -NoClobber

Worried about accidental overwrites? Use -NoClobber to stop Out-File from bulldozing your hard work.

Step 7: Add-Content Goes Wild

Add-Content -Path C:\Temp\* -Filter *.txt -Value "Done"

This command adds the string “Done” to all .txt files in C:\Temp. It’s like sending a memo to every text file in the room. No questions asked.

Summary: Add-Content vs Out-File

  • Both write to files, but behave very differently
  • Add-Content requires strings — use Out-String if needed
  • Out-File preserves formatting and structure
  • Add-Content appends by default
  • Out-File overwrites by default
  • -Append and -NoClobber give you more control with Out-File
  • Add-Content can write to multiple files using wildcards and filters

In the end, choose the cmdlet that fits your situation. Use Out-File when you want formatting. Use Add-Content when you want speed, simplicity, and just a touch of chaos.

Stay tuned for more PoshBytes, where the code is short, the jokes are dry, and the files never overwrite themselves without permission.