6

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?

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Upvoting this, because only after your answer did I grok that $msg isn't being set to a single string, but an array of lines which are by default concatenated with spaces.
Great time saver and hidden gem. Excellent!
10

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

Comments

1

This is a good use for 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.