5

In a PowerShell script, I'm capturing the string output of an EXE file in a variable, then concatenating it with some other text to build an email body.

However, when I do this I find that the newlines in the output are reduced to spaces, making the total output unreadable.

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

Why is this happening, and how can I fix it?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
JSBձոգչ
  • 39,735
  • 16
  • 97
  • 166

2 Answers2

14

Or you could simply set $OFS like so:

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

From man about_preference_variables:

Output Field Separator. Specifies the character that separates the elements of an array when the array is converted to a string.

Keith Hill
  • 184,219
  • 38
  • 329
  • 358
9

Perhaps this helps:

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

You get a list of lines and not a text from other.exe

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


 $a = ('abc', 'efg')
 "Output of other.exe: " +  "`r`n" + ($a -join "`r`n")
bernd_k
  • 11,018
  • 7
  • 41
  • 62