This topic contains 3 replies, has 3 voices, and was last updated by
December 2, 2015 at 7:12 am #32496ParticipantPoints: 1Rank: Member
Building a form to handle some PowerShell stuff and I've hit some odd behaviour with displaying multiline strings.
I'm grabbing lines from a text file with Get-Content and attempting to display them in a textbox (note that other controls and MessageBox exhibit the same behaviour) but the newlines are not being registered.
Eg, a text file containing:
Will display as:
1 2 3 a b c
Newline chars `r, `n and `r`n all correctly add a new line so yes, I can put in a foreach loop and build a new "form friendly" string but this is a very messy approach that I'm hoping won't be necessary.
Running PowerShell 5.0 (but should be compatible with 4.0)
December 2, 2015 at 7:23 am #32497KeymasterPoints: 1,704Rank: Community Hero
What you're seeing is a pretty common gotcha with Get-Content. It reads in your file one line at a time, drops the CRLF at the end of each line, and stores each line as a distinct String object. What you end up with is a collection of Strings. When PowerShell displays a collection of objects in the console, it adds CRLF after each object, so your file looks the same – but that's something the console is doing at display only. If you just feed the collection into a text box – as you've seen – you don't get the CRLF. It's because you don't actually have a multiline string anymore – you have a bunch of single-line strings, which isn't quite the same.
Two potential approaches.
One, pipe the strings to Out-String first. That'll run the display mechanism, which should actually add CRLF to each line, and outputs a single string with all of it.
Two, use Join-Object and join the objects using CRLF as a delimiter. Same basic principle.
December 2, 2015 at 9:57 am #32508MemberPoints: 0Rank: Member
Since you're running PSv4/5, you can also just use the -Raw switch when you call Get-Content. This will load up the whole file as a single string, instead of an array of lines. (The -Raw switch was added to the filesystem provider in PowerShell v3.)
December 3, 2015 at 7:56 am #32561ParticipantPoints: 1Rank: Member
I figured that was the case Don, but the solution is still just as messy. I have a file, but before I can use it I need to join all the lines with a newline delimiter ugh. Messy messy messy.
The -Raw switch is exactly what I was looking for, thank you Dave!
The topic ‘Displaying multiline string in Windows form’ is closed to new replies.