In Powershell, prudent use of parentheses will cause the operation to complete completely before passing data to the next command in the pipeline. The default value for piping Get-Content is to trace line by line for the next command, but with parentheses it should form a complete data set (for example, load all lines) before continuing:
(Get-Content myFile) | Select-String 'MyFilter' | Set-Content myFile
An alternative that can use less memory (I have not tested it) is to only force the execution of the Select-String results before continuing:
(Get-Content myFile | Select-String 'MyFilter') | Set-Content myFile
You can also assign things to a variable as an extra step. Any technique will load content into Powershell session memory, so be careful with large files.
Application: Select-String returns MatchInfo objects. Using Out-File adds superfluous extra empty lines due to the way it tries to format the results as a string, but Set-Content correctly converts each object to its own string when writing, creating better output. Being that you come from * nix and are used for everything that returns strings (whereas Powershell returns objects), one way to force the output of a string is to pass them through foreach , which converts them:
(Get-Content myFile | Select-String 'MyFilter' | foreach { $_.tostring() }) | Set-Content myFile
source share