2010-12-13 82 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

相關問題