Powershell's out-file clears the file when piped from itself

后端 未结 2 2002
死守一世寂寞
死守一世寂寞 2021-01-25 10:44

I am working with the following command:

get-content C:\\somepath\\Setup.csproj | 
        select-string -pattern \'\'          


        
相关标签:
2条回答
  • 2021-01-25 11:11

    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.

    0 讨论(0)
  • 2021-01-25 11:14

    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 ......
    
    0 讨论(0)
提交回复
热议问题