Append data to a file

A question on the forums – the user wanted to append data to a file. This is a common scenario when you’re creating a log file.

There’s 2 easy ways to do this.

Lets create a couple of variables with multi-line data

PS> $data = @’
>> This is
>> multiline data
>>
>> ‘@
PS> $data
This is
multiline data

PS> $data2 = @’
>> This is
>> more multiline
>> data
>> ‘@
PS> $data2
This is
more multiline
data

First you could use Out-File

PS> Out-File -FilePath of.txt -InputObject $data
PS> Out-File -FilePath of.txt -InputObject $data2 -Append
PS> Get-Content -Path of.txt
This is
multiline data

This is
more multiline
data

First time you call Out-File you don’t have to use –Appemd but you can. On subsequent calls use -Append to add the data – if you don’t the file will be overwritten with the new data.

Second option is one you don’t see so much – Add-Content. In earlier versions of PowerShell this was your only option

PS> Add-Content -Path ac.txt -Value $data
PS> Add-Content -Path ac.txt -Value $data2
PS> Get-Content -Path ac.txt
This is
multiline data

This is
more multiline
data

If the file doesn’t exist Add-Content will create it.

Two ways to append data to your file

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s