How to retrieve a specific number of lines from files in PowerShell?


To retrieve the specific number of lines from the beginning or the end of the file, you first need to get the content of the file using Get-Content and then need to pipeline the -First for retrieving the number of files from the beginning and -Last to retrieve the number of lines from the bottom.

Check the below example of retrieving the content of the first 10 lines.

Example

Get-Content D:\Temp\PowerShellaliases.txt -First 10

Output

PS C:\WINDOWS\system32> Get-Content D:\Temp\PowerShellaliases.txt -First 10
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           CFS -> ConvertFrom-String                          3.1.0.0    Microsoft.PowerShell.Utility

To get the content of the last 10 lines from the file.

Example

Get-Content D:\Temp\PowerShellaliases.txt -Last 10

Output

PS C:\WINDOWS\system32> Get-Content D:\Temp\PowerShellaliases.txt -Last 10
Alias           swmi -> Set-WmiInstance
Alias           tee -> Tee-Object
Alias           trcm -> Trace-Command
Alias           type -> Get-Content
Alias           wget -> Invoke-WebRequest
Alias           where -> Where-Object
Alias           wjb -> Wait-Job
Alias           write -> Write-Output

Updated on: 16-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements