Monthly Archive

Categories

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 a file

Comments are closed.