我正在尝试使用新行字符加入一系列名称。我有以下代码
$body = $invalid_hosts -join "`r`n"
$body = "The following files in $Path were found to be invalid and renamed `n`n" + $body
最后,我通过电子邮件发送内容。
$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
当我收到消息时,行The following files in <filepath> were found to be invalid and renamed
具有预期的双倍空格,但$ invalid_hosts的内容全部在一行上。我也尝试过做
$body = $invalid_hosts -join "`n"
和
$body = [string]::join("`n", $invalid_hosts)
两种方式都没有效果。我需要做些什么来完成这项工作?
答案 0 :(得分:19)
将数组传递给Out-String
cmdlet,将它们从字符串对象集合转换为单个字符串:
PS> $body = $invalid_hosts -join "`r`n" | Out-String
答案 1 :(得分:6)
只需输出Out-String(参见https://stackoverflow.com/a/21322311/52277)
即可 $result = 'This', 'Is', 'a', 'cat'
$strResult = $result | Out-String
Write-Host $strResult
This
Is
a
cat
答案 2 :(得分:5)
我不确定如何回答其他所有内容,但为了保证Powershell中的新行,请使用: [环境] :: NewLine代替你的“n”
答案 3 :(得分:3)
今天必须解决这个问题;以为我会分享我的答案,因为问题和其他答案帮助我找到了解决方案。而不是
$body = $invalid_hosts -join "`r`n"
$body = "The following files in $Path were found to be invalid and renamed `n`n" + $body
使用
$MessageStr = "The following files in " + $Path + " were found to be invalid and renamed"
$BodyArray = $MessageStr + $Invalid_hosts
$Body = $BodyArray -join "`r`n"
答案 4 :(得分:2)
我采用了不同的方法,只是替换了换行符
$result -replace("`r`n"," ")
答案 5 :(得分:1)
我当然不是 PowerShell 专家,但我找到了一种更简单的方法。像这样简单地通过管道传送到 Write-Host
:
$array = 'This', 'Is', 'a', 'cat'
$array | Write-Host
Output:
This
Is
a
cat
这是一个与 OP 问题略有不同的用例。它不使用换行符连接数组,但在写入输出时确实提供换行符。