Join an array with newline in PowerShell

join, powershell

Solution

Pipe the array to the `Out-String` cmdlet to convert them from a collection of string objects to a single string:

PS> $body = $invalid_hosts -join "`r`n" | Out-String

Problem

I have an array of names that I'm trying to join using a new line character. I have the following code ``` $body = $invalid_hosts -join "`r`n" $body = "The following files in $Path were found to be invalid and renamed `n`n" + $body ``` Finally, I send the contents via email. ``` $From = "myaddress@domain.com" $To = "myaddress@domain.com $subject = "Invalid language files" Send-MailMessage -SmtpServer "smtp.domain.com" -From $From -To $To -Subject $subject -Body $body ``` When I receive the message, the line `The following files in <filepath> were found to be invalid and renamed` has the expected double space, but the contents of $invalid_hosts are all on one line. I've also tried doing ``` $body = $invalid_hosts -join "`n" ``` and ``` $body = [string]::join("`n", $invalid_hosts) ``` Neither way is working. What do I need to do to make this work?

Original source

Related problems