Add-Content

Mastering PowerShell Cmdlets: Add-Content

Welcome back to Wahmans PowerShell Blog!

Today we will explore a versatile and fundamental PowerShell cmdlet: Add-Content.

According to the official Microsoft documentation, Add-Content “Adds content to the specified items, such as adding words to a file.” In simpler terms, this cmdlet lets you append text or other data to files like text documents, logs, or even scripts—without overwriting the original content.

Why Use Add-Content?

Add-Content is particularly useful when you want to:

  • Log data during script execution
  • Create batch updates to configuration files
  • Automate report building
  • Document activities for auditing

Let’s walk through four examples ranging from beginner to more advanced usage.

Example 1: Append a Single Line to a Text File

This is the most straightforward usage of Add-Content.

Add-Content -Path "C:\Logs\example.txt" -Value "Script executed successfully at $(Get-Date)"

This command appends a line stating the script execution time to example.txt.

Example 2: Append Multiple Lines Using an Array

Let’s say you want to append several lines to a file at once.

$lines = @("User login detected", "Role: Administrator", "Time: $(Get-Date)")
Add-Content -Path "C:\Logs\access_log.txt" -Value $lines

This appends all three lines in order to the file access_log.txt.

Example 3: Append User Input to a File

Allow the user to write a message that gets saved to a file. Useful for interactive scripts.

$input = Read-Host "Enter a note for the log"
Add-Content -Path "C:\Logs\user_notes.txt" -Value "$env:USERNAME: $input at $(Get-Date)"

This appends user input along with the username and timestamp to a file.

Example 4: Log Errors to a File Within a Try/Catch Block

This is an advanced use case for robust error handling in production scripts.

try {
    # Deliberate error for demonstration
    Get-Item "C:\NonexistentFile.txt"
} catch {
    $errorMessage = "[$(Get-Date)] Error encountered: $($_.Exception.Message)"
    Add-Content -Path "C:\Logs\error_log.txt" -Value $errorMessage
}

This logs detailed error information automatically when an exception occurs.

Conclusion

The Add-Content cmdlet is an essential tool in every PowerShell scripter’s toolkit. Whether you’re appending a simple log entry or building robust log tracking into automated processes, it’s a cmdlet worth mastering.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *