How to get the first few lines of a file using Powershell?

Many times system administrators are required to fetch the first few lines of a file. Powershell can help you fetch a specific number of lines from the top, bottom, or from middle of the file.

We will look at the example where we will fetch the first 10 lines of a file using Powershell. You can use the command and use it to fetch any number of lines from the top of the file.

Find the first 10 lines from top of a file using Powershell

For our example, we will consider a text file and fetch the first 10 lines using the Powershell command.

Get-Content d:\test_folder_1\top-lines.txt | Select -first 10

We are using the Get-content cmdlet to read the text file. Once the text file has been read into the memory, the contents are piped to the Select object and we add a switch to fetch the first 10 lines from the file. In the above example, we have specified a text file path that will be read.

The result of this command is displayed below in the screenshot.

Fetch first 10 lines from a text file using Powershell.

On a practical level, you may be required to fetch the content from a file and produce another file to store the results. In other words, we will look at an example wherein we will pull the first 10 lines from a text file. And, then we will send these lines to a new file.

For exporting the fetched lines, we will use the out-file directive in Powershell.

So, in the example below, we will achieve the following tasks:

  • We will get 10 lines from the top of a file
  • We will send these 10 lines to a different file

The command looks like the one below:

Get-content d:\test_folder_1\top-lines.txt | select -first 10 | out-file d:\test_folder_1\top10-lines.txt

The out-file directive helps in sending the output of the command to a new file. This file will contain the top 10 lines of the text file that have been fetched using the get-content command.

Once we execute this command, we will get a new text file. The contents of the file are displayed in the screenshot below:

In most practical scenarios, you will be reading a CSV file from the top and creating a new file containing a specific number of lines from the top or bottom of the file. Powershell offers a simple and fast approach to achieving the desired objective using the get-content cmdlet and the out-file directive command.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Rajesh Dhawan

Rajesh Dhawan is a technology professional who loves to blog about smart wearables, Cloud computing and Microsoft technologies. He loves to break complex problems into manageable chunks of meaningful information.