Home » How to Get Content and Remove First Line in PowerShell

How to Get Content and Remove First Line in PowerShell

To remove first line from a file using PowerShell, you can use the Get-Content and Set-Content cmdlets.

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

Method: Get content and remove first line

$dataWithoutFirstLine = Get-Content -Path $filePath | Select-Object -Skip 1 Set-Content -Path $filePath

This example will read the content of a file ,remove first line and save the remaining content back to the file.

The following example shows how to use this method.

How to Remove First Line in PowerShell

To remove the first line from a file using PowerShell, use the Get-Content cmdlet to read the file content and then skip the first line using the -Skip parameter and save the remaining content back to the file.

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

# Get content and remove first line
$dataWithoutFirstLine = Get-Content -Path $filePath | Select-Object -Skip 1

# save the content back to the file
$dataWithoutFirstLine | Set-Content -Path $filePath

Output:

PowerShell get content and remove first line
PowerShell get content and remove first line

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

We then use the Get-Content cmdlet to read the file content specified by $filePath and then pipe the content to the Select-Object command to skip the first line using the -Skip 1 parameter and store the file content without a first line in the $dataWithoutFirstLine variable.

Finally, the $dataWithoutFirstLine pipe to the Set-Content variable to save the remaining content back to the file.

After running the script, it removes the first line from the file and saves the remaining content to the file.

Conclusion

I hope the above article on getting content and removing the first line from a file in PowerShell is helpful to you.

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