Home » How to Get First Line of File in PowerShell

How to Get First Line of File in PowerShell

To get the first line of a file using PowerShell, you can use the Get-Content cmdlet with the -First or -TotalCount parameter.

The following method shows how you can do it with syntax.

Method 1: Using the Get-Content with -First parameter

Get-Content -Path $filePath -First 1

This example will return the first line of a file.

Method 2: Using the Get-Content with -TotalCount parameter

Get-Content -Path $filePath -TotalCount 1

This example will read the first line of the specified file and display it.

The following examples show how you can use these methods.

Get First Line of a File Using the Get-Content with -First in PowerShell

You can use the Get-Content cmdlet with the -First parameter to get the first line of a file.

# specify the file path
$filePath = "C:\temp\log\system_log.txt"

# read the file and get first line of a file
Get-Content -Path $filePath -First 1

Output:

PowerShell get first line of a file using Get-Content -First 1
PowerShell get first line of a file using Get-Content -First 1

In this script, we define a variable $filePath that stores the path to the text file.

We then use the Get-Content cmdlet to read the specified file $filePath and use the -First parameter to get the first line of a file.

The -First 1 instructs the PowerShell to return only the first line of a file.

After running the script, it will read the file and return the first line of a file.

Get the First Line of a File Using the Get-Content with -TotalCount in PowerShell

Another way to get the first line of a file is to use the Get-Content cmdlet with the -TotalCount parameter.

# specify the file path
$filePath = "C:\temp\log\system_log.txt"

# read the file and get first line of a file
Get-Content -Path $filePath -TotalCount 1

Output:

PowerShell get first line of a file using Get-Content -TotalCount 1
PowerShell get first line of a file using Get-Content -TotalCount 1

In this script, we define a variable $filePath that stores the path to the text file.

We then use the Get-Content cmdlet to read the specified file $filePath and use the -TotalCount parameter to get the first line of a file.

The -TotalCount 1 instructs the PowerShell to return only the first line of a file.

After running the script, it will read the file and return the first line of a file.

Conclusion

I hope the above article on getting the first line of a file using PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.