PowerShell: How to Get First Line of File


You can use the following methods in PowerShell to get the first line of a file:

Method 1: Get First Line of File

$my_file = "c:\path\to\file\data.txt"
Get-Content -Path $my_file -TotalCount 1

This particular example will return only the first line from the file located at the path we specified in $my_file.

Method 2: Get First N Lines of File

$my_file = "c:\path\to\file\data.txt"
Get-Content -Path $my_file -TotalCount 5

This particular example will return the first five lines from the file located at the path we specified in $my_file.

Method 3: Get First N Lines of File and Export to New File

$my_file = "c:\path\to\file\data.txt"
Get-Content -Path $my_file -TotalCount 5 | Out-File "first_five.txt"

This particular example will get the first five lines from the data.txt file and export them to a new file named first_five.txt.

The following examples show how to use each method in practice.

Example 1: Get First Line of File Using PowerShell

Suppose we have a file named teams.txt that contains ten total lines with the names of various basketball teams.

We can use the following syntax to get only the first line from this file:

$my_file = "c:\path\to\file\data.txt"
Get-Content -Path $my_file -TotalCount 1

The following screenshot shows how to use this syntax in practice:

PowerShell get first line in file

By using -TotalCount 1 we are able to retrieve only the first line from this file.

Example 2: Get First N Lines of File Using PowerShell

Once again suppose we have a file named teams.txt that contains ten total lines with the names of various basketball teams.

We can use the following syntax to get the first five lines from this file:

$my_file = "c:\path\to\file\data.txt"
Get-Content -Path $my_file -TotalCount 5

The following screenshot shows how to use this syntax in practice:

PowerShell get first 5 lines from file

By using -TotalCount 5 we are able to retrieve the first five lines from this file.

Example 3: Get First N Lines of File and Export to New File Using PowerShell

Suppose that we would like to get only the first five lines from the file named teams.txt and then export these five lines to a new file named first_five.txt.

We can use the following syntax to do so:

$my_file = "c:\path\to\file\data.txt"
Get-Content -Path $my_file -TotalCount 5 | Out-File "first_five.txt"

The following screenshot shows how to use this syntax in practice:

PowerShell get first n lines and export to new file

By using Out-File we are able to export the first five lines from the teams.txt file to a new file named first_five.txt.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Get First Item in Array
PowerShell: How to Get First Character of String
PowerShell: How to Get Last Folder in Path

Leave a Reply