Writing array elements one per line in a string

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Ryk McDorman Ryk McDorman 3 years, 10 months ago.

  • Author
    Posts
  • #7904
    Profile photo of Ryk McDorman
    Ryk McDorman
    Participant

    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:

    red

    blue

    yellow

    ?? 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.

    Thanks.

  • #7908
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
    Profile photo of Ryk McDorman
    Ryk McDorman
    Participant

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

    Thanks for the assistance, Don!

You must be logged in to reply to this topic.