Search code examples
powershellherestring

Process HereString line by line


I would like to define a HereString then work with it line by line. Initially I figured the lines would be innate in the HereString, so I could foreach ($line in $hereString), and when that didn't work I tried Get-Content $hereString. No joy in either case. The goal is just to work on a bit of code that will eventually manipulate entire text files, so I could quickly convert to using a small example text file while implementing this, but now I am curious if HereStrings even CAN be worked with line by line, without splitting somehow.


Solution

  • Since your intent is to use this to process files, I'd start with something like this:

    $file = 'c:\testfiles\testfile1.txt'
    
    $textdata = 
    @'
    Line1
    Line2
    Line3
    '@
    
    $textdata | Set-Content $file
    
    $lines = Get-Content $file
    
    foreach ($line in $lines) {}
    

    Now you're testing in the same environment that you'll be working with in production, and you can experiment with different I/O methods as well as different data parsing and manipulation methods. Knowing how to do this will become more important from a performance standpoint as the size and number of files involved scales upwards.