Coding Ref

Add-Content in PowerShell

Add-Content in PowerShell

The Add-Content cmdlet in PowerShell is used to add new content to the end of a file. This cmdlet takes the path and name of the file as input, and the content to be added to the file as an argument. It then appends the specified content to the end of the file.

Examples

Example 1: Add text to the end of a file

For example, to add the text "This is a new line of text" to the end of a file named "myfile.txt" in the current directory, you can use the following PowerShell command:

Add-Content "myfile.txt" "This is a new line of text"

This command will add the specified text to the end of the "myfile.txt" file in the current directory.

If the file does not exist, it will be created automatically.

If the file already contains other content, the new content will be added after the existing content.

Example 2: Add a newline or multiple lines

To add a new line to a file using the Add-Content cmdlet in PowerShell, you can use the `n escape sequence to represent a new line.

This escape sequence tells PowerShell to insert a new line at the specified location in the content being added to the file.

For example, to add the text "This is the first line" and "This is the second line" to a file named "myfile.txt" in the current directory, with each line appearing on a separate line in the file, you can use the following PowerShell command:

Add-Content "myfile.txt" "This is the first line`nThis is the second line"
It is important to note that the `Add-Content` cmdlet only adds content to the end of a file.

Conclusion

The Add-Content cmdlet is useful for adding new information to an existing file without overwriting or modifying the existing content. It is commonly used in PowerShell scripts and automation tasks to update files with new data or information.

You'll also like

Related tutorials curated for you

    How to sort and filter data in PowerShell

    How to write multiple-line comments in PowerShell

    How to get the date in PowerShell

    How to create a directory in PowerShell

    How to pause in PowerShell

    Dictionaries in PowerShell

    How to select an object in PowerShell

    How to get processes in PowerShell

    What is a PowerShell Hashtable?

    How to copy and paste into PowerShell

    How to list all installed modules in PowerShell

    What is null in PowerShell?