在PowerShell字符串中保留换行符

6
在PowerShell脚本中,我将一个EXE文件的字符串输出存储在一个变量中,然后将其与其他文本连接起来构建电子邮件正文。
然而,当我这样做时,我发现输出中的换行符被缩减为空格,使得整个输出无法阅读。
# Works fine
.\other.exe

# Works fine
echo .\other.exe

# Works fine
$msg = other.exe
echo $msg

# Doesn't work -- newlines replaced with spaces
$msg = "Output of other.exe: " + (.\other.exe)

为什么会发生这种情况,我该如何解决?
3个回答

16

或者您可以像这样简单地设置$OFS:

PS> $msg = 'a','b','c'
PS> "hi $msg"
hi a b c
PS> $OFS = "`r`n"
PS> "hi $msg"
hi a
b
c

来自 man about_preference_variables:

输出字段分隔符。指定在将数组转换为字符串时,分隔数组元素的字符。


1
点赞,因为只有在你的回答之后我才明白$msg不是被设置为单个字符串,而是一个由多行组成的数组,默认情况下用空格连接。 - JSBձոգչ
非常省时且隐藏的宝石。太棒了! - Scott Saad
非常好的答案!谢谢! - LPChip

10

也许这可以帮助:

$msg = "Output of other.exe: " + "`r`n" + ( (.\other.exe) -join "`r`n")

从 other.exe 获得的是一系列行,而不是文本。

$a = ('abc', 'efg')
 "Output of other.exe: " + $a


 $a = ('abc', 'efg')
 "Output of other.exe: " +  "`r`n" + ($a -join "`r`n")

1

这是使用 Out-String 的一个好例子。

Write-Output "My IP info: $(ipconfig.exe | Out-String)"

My IP info:
Windows IP Configuration


Ethernet adapter Ethernet 2:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : 2222::2222:2222:2222:5150%4
   IPv4 Address. . . . . . . . . . . : 192.168.1.155
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接