在PowerShell字符串中保留换行符

JSB*_*ոգչ 4 string powershell newline

在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)
Run Code Online (Sandbox Code Playgroud)

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

Kei*_*ill 12

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

PS> $msg = 'a','b','c'
PS> "hi $msg"
hi a b c
PS> $OFS = "`r`n"
PS> "hi $msg"
hi a
b
c
Run Code Online (Sandbox Code Playgroud)

来自man about_preference_variables:

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


ber*_*d_k 8

也许这有助于:

$msg = "Output of other.exe: " + "`r`n" + ( (.\other.exe) -join "`r`n")
Run Code Online (Sandbox Code Playgroud)

您获得了一个行列表,而不是来自other.exe的文本

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


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