Using Add-Content to output array to a txt file

Welcome Forums General PowerShell Q&A Using Add-Content to output array to a txt file

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years, 7 months ago.

  • Author
  • #5323

    Topics: 1562
    Replies: 0
    Points: 0
    Rank: Member

    by RLewis123 at 2012-12-05 11:11:17

    I have an array that contains a number of items with a single item on each line. I need to append a txt file with this array info but when I do that the .txt file has all the lines appear on a single line. How can I take this array info and use it to append a file and still get the newlines that are in it to show up?

    I've used a foreach on the array like this:
    foreach ($lineitem in $Array){add-content -path $LogFile "$lineitem`n"}

    by iHunger at 2012-12-05 11:26:20

    Just guessing, but you might need a `r`n instead of just `n.

    by RLewis123 at 2012-12-05 11:58:05

    Tried it – no joy. Thanks anyway.

    The Array appears fine onscreen, in an e-mail and even works if I output to a CSV format file but the minute I'm outputting to a .TXT format file and opening in Notepad it all displays on a single line.

    by RichardSiddaway at 2012-12-05 12:16:31

    Does this solve your problem?
    $data = "AAA", "BBB", "CCCC", "DDD"

    Add-Content -Path C:\test\test.txt -Value $data

    get-content -Path C]

    Just makes sure you have a line feed after the last line in the file before you add the array

    by RLewis123 at 2012-12-05 13:15:23

    Richard – The Array I have is being created by code that looks like this:

    $array += "$strComputer1 blah1`n"
    $array += "$strComputer2 blah2`n"
    $array += "$strComputer3 blah3`n"
    $array += "$strComputer4 blah4`n"

    In the end this is creating an array that appears to have newline chars in it but displays on a single line when placed into a TXT file.

    by RLewis123 at 2012-12-05 16:22:59

    OK – the `r did the trick after all – inserted it at a different location. Many thanks!

The topic ‘Using Add-Content to output array to a txt file’ is closed to new replies.