Add-Content is a PowerShell cmdlet used to append content to the end of an existing file or to create a new file with the specified content. This cmdlet is part of the Microsoft.PowerShell.Management module and is commonly used for file manipulation tasks.
Syntax: Add-Content [-Path] <String[]> [-Value] <Object[]> [<CommonParameters>]
Key features and usage:
- Append content: It adds new content to the end of an existing file without overwriting the current content.
- Create new files: If the specified file doesn’t exist, Add-Content will create it and add the content.
- Multiple files: You can specify multiple file paths to add content to several files simultaneously.
- Various input types: It accepts different types of input, including strings, numbers, and even the output from other cmdlets.
- Encoding support: You can specify the encoding for the content being added.
- Force parameter: Use -Force to add content to read-only files.
- PassThru parameter: When used, it returns an object representing the added content.
- LiteralPath parameter: Allows you to specify file paths that contain wildcard characters.
Examples:
- Add a single line to a file:
Add-Content -Path "C:\example.txt" -Value "New line of text"
- Add multiple lines to a file:
Add-Content -Path "C:\example.txt" -Value "Line 1", "Line 2", "Line 3"
- Add content to multiple files:
Add-Content -Path "file1.txt", "file2.txt" -Value "Same content for both files"
- Add content with specific encoding:
Add-Content -Path "C:\example.txt" -Value "Text with encoding" -Encoding UTF8
- Add content from another cmdlet:
Get-Process | Add-Content -Path "C:\processes.txt"
Add-Content is a versatile cmdlet for adding data to files in PowerShell, offering flexibility in handling various file operations and content types.