PowerShell — Get-Content slow?

In PowerShell, the cmdlet Get-Content is used to read a file. Usually you just give the path of a file name as below:

Get-Content -Path "c:\temp\test.txt"

When the file is small, you won’t notice anything wrong. But when it’s quite big with thousands of lines, you might notice it’s extremely slow to display.

This is to do with the way Get-Content works. For each object returned from the pipe, it adds a bunch of extra information to that object in the form of NoteProperty. And by default Ge-Content reads one line at a time!

PS D:\Users\joe> Get-Content .\test.txt|Get-Member -MemberType NoteProperty

   TypeName: System.String

Name         MemberType   Definition
----         ----------   ----------
PSChildName  NoteProperty string PSChildName=test.txt
PSDrive      NoteProperty PSDriveInfo PSDrive=D
PSParentPath NoteProperty string PSParentPath=D:\Users\joe
PSPath       NoteProperty string PSPath=D:\Users\joe\test.txt
PSProvider   NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\FileSystem
ReadCount    NoteProperty long ReadCount=1

Fortunately this cmdlet has an option “-ReadCount” and the default value is 1 which means read one line at a time. You can imagine why Get-Content gets slow when it handles thousands of lines one by one and adding extra information for each object (each line) returned.

As the help indicates:”This parameter does not change the content displayed, but it does affect the time it takes to display the content. As the value of ReadCount increases, the time it takes to return the first line increases, but the total time for the operation decreases. This can make a perceptible difference in large items. A value of 0 (zero) sends all of the content at one time.

So to speed up the output, we can use the option “-ReadCount” with “0” or a much bigger value.

Get-Content .\test.txt -ReadCount 0
Get-Content .\test.txt -ReadCount 500

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s