What is the Add-Content cmdlet in PowerShell?

Overview

The Add-Content cmdlet is used to write content into a file. It appends the content into a file if it exists. It creates the file if doesn't exist.

Syntax

Add-Content -Path "path to file" -Value "new content"

Parameters

The function takes the following mandatory parameters:

  • Path: We provide the path to the file.
  • Value: We provide content to this parameter.

Return value

It appends the content provided by the Value parameter to the file provided by the Path parameter.

Example

#!/usr/bin/pwsh -Command
#Write content to a file
Set-Content -Path "./data.txt" -Value "This is written by Set-Content cmdlet `n"
#Append content to a file
Add-Content -Path "./data.txt" -Value "This is written by Add-Content cmdlet `n"
#Read content from a file
Get-Content -Path "./data.txt"

Explanation

  • Line 4: We write content to a file using the Set-Content cmdlet.
  • Line 7: We append the content to the same file, data.txt, using the Add-Content cmdlet, to which Set-Content cmdlet also wrote.
  • Line 10: We display the content of the same file, data.txt, using the Get-Content cmdlet.

From the output, we can see that the content written by Set-Content is not overwritten by the Add-Content cmdlet.

Free Resources