Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove last couple of lines in the text file with powershell

I have a text file as follows

Apple=1

Manggo=1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Appleandmanggobellongsto=Jimmy

Apple=1

Manggo=1

Appleandmanggobellongsto=Dave

Apple=1

Manggo=1

Appleandmanggobellongsto=Carlton

I want to remove the last 3 lines and this is what I want to achieve:

Apple=1

Manggo=1

Appleandmanggobellongsto=Jimmy

Apple=1

Manggo=1

Appleandmanggobellongsto=Dave

$File = c:\Text.txt

get-content $File | select-object -skiplast 3 | set-contect $File

but I dont get anything.

please tell me what I did wrong?

>Solution :

Set-Contect is not a built-in cmdlet, assuming you meant Set-Content then the issue is that you’re trying to read and write to the same file in a single pipeline which results in a blank file. You need to consume the output from Get-Content first and then write to the file, for that you can use the grouping operator ( )

$File = 'c:\Text.txt'
(Get-Content $File) | Select-Object -SkipLast 3 | Set-Content $File
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading