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?
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.
`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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With