'Powershell - Fastest way to write large body of text to a file

In terms of runtime performance, which is the fastest method in powershell to write a large body of text into a file?



Solution 1:[1]

$sw = new-object system.IO.StreamWriter(<my file path>)
$sw.write(<my large body of text>)
$sw.close()

Solution 2:[2]

Guillaume Bordier wrote a nice article about the different methods of writing to a file.

From the article's conclusion:

Method               - Time to completion
‘>>’                 - 29 s
Out-file and [Array] - 27 s
export-csv           - 22 s
StreamWriter         - 1.5 s

The fastest way to write to a file (by a margin) is using StreamWriter.

Solution 3:[3]

Definitely read the excellent article from PS admin blog (with code example).

Summary is to avoid foreach-object loop and use following for write to file:

  • .net File WriteLine
  • .net StreamWriter WriteLine

Link: https://www.google.com/amp/s/powershelladministrator.com/2015/11/15/speed-of-loops-and-different-ways-of-writing-to-files-which-is-the-quickest/amp/

Also a good explanation : https://powershellexplained.com/2017-03-18-Powershell-reading-and-saving-data-to-files/#faster-reads-with-systemiofile

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Brabant
Solution 2 Mario Tacke
Solution 3