Author Posts

June 26, 2013 at 2:18 pm

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.

June 26, 2013 at 3:19 pm

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.

June 26, 2013 at 4:10 pm

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

Thanks for the assistance, Don!