Copy specific lines from a text file to separate file using powershell

Question:

I am trying to get all the lines from an Input file starting with %% and paste it into Output file using powershell.

Used the following code, however I am only getting last line in Output file starting with %% instead of all the lines starting with %%.

I have only started to learn powershell, please help

Answer:

You are looping over the lines in the file, and setting each one as the whole content of the file, overwriting the previous file each time.

You need to either switch to using Add-Content instead of Set-Content, which will append to the file, or change the design to:

Which you would more typically write as:

and in the shell, you might write as

Where the whole file is filtered, and then all the matching lines are sent into Set-Content in one go, not calling Set-Content individually for each line.

NB. PowerShell is case insensitive by default, so -like and -ilike behave the same.

Source:

Copy specific lines from a text file to separate file using powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply