2010-12-13 119 views
4

在PowerShell脚本中,我捕获变量中EXE文件的字符串输出,然后将它与其他一些文本连接起来构建一个电子邮件正文。在PowerShell字符串中保留换行符

但是,当我这样做时,我发现输出中的换行符会减少到空格,从而导致总输出不可读。

# 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) 

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

回答

8

也许这可以帮助:

$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") 
11

行的列表,而不是文本或者你可以简单地设置$ 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

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

+0

Upvoting这个,因为只有在你的回答结束后我才发现'$ msg'没有被设置为一个单独的字符串,而是一个*数组*,它们默认与空格连接。 – 2010-12-13 21:00:59

+0

很棒的时间节省和隐藏的宝石。优秀! – 2011-01-19 20:16:02