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 fileSet-Content -Path "./data.txt" -Value "This is written by Set-Content cmdlet `n"#Append content to a fileAdd-Content -Path "./data.txt" -Value "This is written by Add-Content cmdlet `n"#Read content from a fileGet-Content -Path "./data.txt"
Explanation
- Line 4: We write content to a file using the
Set-Contentcmdlet. - Line 7: We append the content to the same file,
data.txt, using theAdd-Contentcmdlet, to whichSet-Contentcmdlet also wrote. - Line 10: We display the content of the same file,
data.txt, using theGet-Contentcmdlet.
From the output, we can see that the content written by Set-Content is not overwritten by the Add-Content cmdlet.