Reputation: 82341
I am working with the following command:
get-content C:\somepath\Setup.csproj |
select-string -pattern '<None Include="packages.config" />' -notmatch |
Out-File -filepath C:\somepath\Setup.csproj -force
The idea is to remove any lines in Setup.csproj that have the text <None Include="packages.config" />
.
However, when I run the above command, my Setup.csproj file is emptied (it goes from have a bunch of text to having no test).
But if I change the command to output to a new file, Setup2.csproj, then the new file is created and has the content I want:
get-content C:\somepath\Setup.csproj |
select-string -pattern '<None Include="packages.config" />' -notmatch |
Out-File -filepath C:\somepath\Setup2.csproj -force
This works fine, and I suppose I could then delete the original and rename Setup2.csproj to be Setup.csproj, but if it can be done in one step, I would prefer it.
Is there a way to use the get-content and select-string methods above and then call Out-File on the SAME file?
(Note, I got the above example from this question.)
Upvotes: 1
Views: 309
Reputation: 73586
The pipeline transfers individual items, not waiting for the entire output of a preceding command to be accumulated, so the pipeline is initialized at its creation in the begin { }
block of each part. In your case the output file stream is created before the actual processing starts, thus overwriting the input.
Enclose the command in parentheses:
(Get-Content C:\somepath\Setup.csproj) | Select-String ......
It forces complete evaluation of the enclosed command before the pipeline starts, in this case the entire file contents is fetched as an array of strings and then this array is fed into the pipeline.
It's basically the same as storing in a temporary variable:
$lines = Get-Content C:\somepath\Setup.csproj
$lines | Select-String ......
Upvotes: 2
Reputation: 9133
Could you please try this:
$filtered_content = Get-Content C:\somepath\Setup.csproj | select-string -pattern '<None Include="packages.config" />' -NotMatch ;
Remove-Item C:\somepath\Setup.csproj -Force ;
New-Item C:\somepath\Setup.csproj -type file -force -value "$filtered_content" ;
Tested in local with one file.
Upvotes: 0