You can use the following syntax in PowerShell to remove the last line from a file:
$data = Get-Content teams.txt
$data[0..($data.count-2)] | Out-File teams_new.txt
This particular example will remove the last line from the file named teams.txt and save the results in a new file named teams_new.txt.
Here is how this syntax works:
- First, we use the Get-Content cmdlet to retrieve all lines from the file named teams.txt.
- Then, we use bracket notation to return all lines starting from index position 0 and ending at the index position equal to the total count of lines with 2 subtracted, which represents the second to last line.
- We then use the Out-File cmdlet to export these results to a new file named teams_new.txt.
The following example shows how to use this syntax in practice.
Example: How to Remove Last Line from a File in PowerShell
Suppose that we have a file named teams.txt in our current directory that contains information about various basketball teams.
We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to remove the last line from this file.
We can use the following syntax to do so:
$data = Get-Content teams.txt
$data[0..($data.count-2)] | Out-File teams_new.txt
The following screenshot shows how to use this syntax in practice:

Notice that when we use the Get-Content cmdlet to view the contents of the new file named teams_new.txt we can see that it contains all of the lines from the original file with the last line removed.
Note: You can find the complete documentation for the Out-File cmdlet in PowerShell here.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to Add Text to Specific Line in a File
PowerShell: How to Add Text to Each Line in a File
PowerShell: How to Save Each Line of Text File as Array
