Writing array elements one per line in a string

Welcome Forums General PowerShell Q&A Writing array elements one per line in a string

This topic contains 2 replies, has 2 voices, and was last updated by

5 years, 9 months ago.

  • Author
  • #7904

    Points: 1
    Rank: Member

    I have some items in an array which need to be written to out-printer, one per line.  Easy enough while they're still in an array,  but I need to list them in the middle of some other text, but still showing each on its own line. For simplicity's sake, below is an example:

    $test = 'red', 'blue', 'yellow'
    $myString = "These are colors: $test"

    This yields:  These are colors: red blue yellow

    How can I get it to yield:

    These are colors:




    ?? I'm sure there's an easy way to do this.  I understand that it's due to the fact that I'm forcing the array contents into a string, but I've tried a few ways of inserting `n`r, but nothing I've tried works. Also my search-fu didn't yield any solutions to the problem.


  • #7908

    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    So, couple things. You're relying a bit on some under-the-hood sneakery PowerShell does when you give it a variable, in double quotes, that contains multiple objects. You won't get a ton of control over that behavior. What you probably need to do is join the array into a string, using CRLF as a delimiter.

    $string = $test -join "-n"

    Except instead of dash-n, put backtick-n. The forums software sometimes freaks about back ticks, so I didn't type it here. Anyway, backtick-N is a newline. Experiment a bit; you may need a backtick-r and backtick-n to get newline and return. The -join operator will take all the elements in the array and merge them into a single string, separated by the delimiter that follows the operator.

  • #7909

    Points: 1
    Rank: Member

    Groovy — that worked!  I had made some split/join attempts, but never successful.

    Thanks for the assistance, Don!

The topic ‘Writing array elements one per line in a string’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort