Search code examples
powershellstreamwriter

Powershell - Streamwriter


I need to write to many files as quickly as possible but I'm not getting the results I want using Streamwriter the way I'm using. For example, if I write...

$File = "c:\somefile"
$Contents = get-content $File
$Contents | set-content $File

So read the contents of the file, do nothing, and write it back... The file is exactly the same. However if I write...

$File = "c:\somefile"
$Contents = get-content $File
$stream = [System.IO.StreamWriter] $File
$stream.WriteLine("$contents")
$stream.close()

Then the file looks as though all line breaks have been ignored and is a bit of a mess. What do I need to do to get it write properly? Many thanks!


Solution

  • A Few Points

    Get-Content and Set-Content

    Get-Content as you are invoking it reads the file line by line (it doesn't give you the line breaks). So if you do this:

    $Contents = Get-Content $File
    

    Then $Contents contains an array of strings that represent the lines in the file.

    By sending that back out to Set-Content (which knows how to handle an array or pipeline of strings) it will write lines.

    Arrays in Strings

    When you use "$contents" the array items will be joined with spaces, not newlines, so when you use $stream.WriteLine you are writing a single string with one line break at the end.

    Fixing It

    1. Use Get-Content $File -Raw to read the whole file at once if it's PowerShell 3+, or use the following to make it into one string yourself.

      $content = (Get-Content $File) -join "`r`n" 
      
    2. Don't do that, and instead use this:

      $stream.Write(($content -join "`r`n"))
      

    Note, I'm using Write() and not WriteLine() because you don't need to insert an extra line at the end of the file (unless you do, but this could get confusing, might want to add it to the content instead).