There may come a time when you want to display just a few lines from a text file. The following PowerShell code can be used to achieve this.
The examples will be based upon a sample text file containing the lines:
In this example, the parameter TotalCount of the Get-Content cmdlet specifies the number of lines from the beginning of a file. The default is -1 (list all lines).
Get-Content -Path myfile.txt -TotalCount 3
You can also achieve this with:
Get-Content myfile.txt -First 3
Doing this from the other end, the Get-Content cmdlet parameter Tail lists lines from the end of the file. This parameter specifies the number of lines from the end of a file.
Get-Content -Path myfile.txt -Tail 3
First and last few lines.
If you really wanted to, you could pipe the output from the Get-Content cmdlet into the Select-Object and make use of the First and Last parameters to look at the first few or last lines in the file.
- First – Gets only the specified number of objects. Enter the number of objects to get.
- Last – Specifies the number of objects to select from the end of an array of input objects.
Get-Content -Path myfile.txt | Select-Object -First 3
Get-Content -Path myfile.txt | Select-Object -Last 4
Lines in the middle of the file.
To look at lines other than the first or last, we could use the Select-Object parameter Index.
From the documentation:
Selects objects from an array based on their index values. Enter the indexes in a comma-separated list.
Indexes in an array begin with 0, where 0 represents the first value and (n-1) represents the last value. IE, the array is zero-based.
This means we have to subtract 1 from the line number(s) in question. To look at lines 4,5 and 6 inclusive, we have to specify line numbers 3,4 and 5.
Get-Content -Path myfile.txt | Select-Object -Index 3,4,5
will give you:
Of course, if you’d like to skip some lines, then use the following:
Get-Content -Path myfile.txt | Select-Object -Skip 4