Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join an array with newline in PowerShell

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 = "[email protected]"
$To = "[email protected]
$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?

like image 416
Robbert Avatar asked Nov 19 '13 20:11

Robbert


People also ask

How do I concatenate a new line in PowerShell?

Using PowerShell newline in Command To add newline in the PowerShell script command, use the` (backtick) character at the end of each line to break the command into multiple lines.

What is the newline character in PowerShell?

`n is used in Powershell to append a new line to the standard output. The use of `n in Powershell is similar to \n in C++ or Java. The backtick character (`) represents an escape character in Powershell.

How do you join strings in PowerShell?

In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator.


2 Answers

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
like image 120
Shay Levy Avatar answered Oct 13 '22 01:10

Shay Levy


It is sufficient just pipe to Out-String (see https://stackoverflow.com/a/21322311/52277)

 $result = 'This', 'Is', 'a', 'cat'
 $strResult = $result  | Out-String
 Write-Host $strResult
This
Is
a
cat
like image 18
Michael Freidgeim Avatar answered Oct 13 '22 01:10

Michael Freidgeim