PowerShell for Windows Admins

Jan 31 2017   2:17PM GMT

Append data to a file

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: