Displaying multiline string in Windows form

Tagged: ,

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Deadly-Bagel Deadly-Bagel 10 months, 4 weeks ago.

  • Author
  • #32496
    Profile photo of Deadly-Bagel

    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)

  • #32497
    Profile photo of Don Jones
    Don Jones

    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.

  • #32508
    Profile photo of Dave Wyatt
    Dave Wyatt

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

  • #32561
    Profile photo of Deadly-Bagel

    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!

You must be logged in to reply to this topic.