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

PowerShellMicrosoft TechnologiesSoftware & Coding

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.


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


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                    Microsoft.PowerShell.Utility

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


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


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
Published on 16-Mar-2020 07:49:31