Reading a Text File from PowerShell
The Get-Content cmdlet gets the content of the item at the location specified by the path, such as the text in a file. It reads the content one line at a time and returns a collection of objects, each of which represents a line of content.


For example, following command displays the contents of the file C:\Scripts\Test.txt:


Code:

Get-Content c:\scripts\test.txt



Following command gets the first 50 lines of the test.txt file and stores them in the Sample.txt file. The command uses the Get-Content cmdlet to get the text in the file. (The name of Path parameter, which is optional, is omitted.) The TotalCount parameter limits the content retrieved to the first 50 lines. The pipeline operator (|) sends the result to the Set-Content cmdlet, which places it in the Sample.txt file.


Code:

Get-Content "c:\scripts\test.txt" -TotalCount 50 | Set-Content "Sample.txt"



Because Get-Content automatically creates an array consisting of each line in the file, that means you can also use the Measure-Object cmdlet to easily count the number of lines in the file:


Code:

Get-Content c:\scripts\test.txt | Measure-Obj



What if you want to return only the first x number of lines in the file? In that case simply add the -totalcount parameter followed by the number of lines to retrieve. This command returns only the first five lines in the file Test.txt:


Code:

Get-Content c:\scripts\test.txt -totalcount 5



To get the last five lines in the text file simply read the file using Get-Content, then have Select-Object pick out the last five items for you:


Code:

Get-Content c:\scripts\test.txt | Select-Object -last 5



Get-Content Aliases:


  • gc
  • type
  • cat