Writing Text Information Fast

by Jun 7, 2013

If you want to write plain text information to a file, don't use Out-File. Instead, use Set-Content. It is much faster:

$tempfile1 = "$env:temp\tempfile1.txt"
$tempfile2 = "$env:temp\tempfile2.txt"
$tempfile3 = "$env:temp\tempfile3.txt"

$text = Get-Content -Path C:\Windows\WindowsUpdate.log

# see how long it takes to write this with Out-File
Measure-Command {
  $text | Out-File -FilePath $tempfile1
}

# see how long it takes to write this with Set-Content
Measure-Command {
  $text | Set-Content -Path $tempfile2 -Encoding Unicode
}

# see how long it takes to write this with Set-Content
Measure-Command {
  Set-Content -Path $tempfile3 -Encoding Unicode -Value $text
}

Depending on how large the windowsupdate.log file is on your machine, you get back varying results. However, Set-Content is more than twice as fast, and if you submit the text to the parameter -Value rather than sending it over the (slow) pipeline, the overall result is even 6x as fast or better.

Use Out-File only if you want to write objects to file. The primary reason why Out-File is slower is: it tries and converts objects to plain text. Set-Content writes the text as-is – which is all you need if you wanted to write plain text in the first place.

Twitter This Tip! ReTweet this Tip!