【问题标题】:Powershell's out-file clears the file when piped from itselfPowershell 输出文件在从自身传输时清除文件
【发布时间】:2017-02-25 22:08:37
【问题描述】:

我正在使用以下命令:

get-content C:\somepath\Setup.csproj | 
        select-string -pattern '<None Include="packages.config" />' -notmatch | 
        Out-File -filepath C:\somepath\Setup.csproj -force

这个想法是删除 Setup.csproj 中包含文本 &lt;None Include="packages.config" /&gt; 的所有行。

但是,当我运行上述命令时,我的 Setup.csproj 文件被清空(它从有一堆文本变为没有测试)。

但如果我将命令更改为输出到新文件 Setup2.csproj,则新文件已创建并具有我想要的内容:

get-content C:\somepath\Setup.csproj | 
        select-string -pattern '<None Include="packages.config" />' -notmatch | 
        Out-File -filepath C:\somepath\Setup2.csproj -force

这很好用,我想我可以删除原来的并将 Setup2.csproj 重命名为 Setup.csproj,但如果可以一步完成,我会更喜欢它。

有没有办法使用上面的 get-content 和 select-string 方法,然后在 SAME 文件上调用 Out-File?

(注意,我从question得到了上面的例子。)

【问题讨论】:

  • (get-content C:\somepath\Setup.csproj)
  • @PetSerAl 和 wOxxOM - 就是这样!也学到了一些新东西。如果您作为答案发布,我会接受!

标签: powershell


【解决方案1】:

管道传输单个项目,而不是等待前面命令的整个输出被累积,因此管道在每个部分的 begin { } 块中创建时被初始化。在您的情况下,输出文件流是在实际处理开始之前创建的,因此会覆盖输入。

将命令括在括号中:

(Get-Content C:\somepath\Setup.csproj) | Select-String ......

它强制在管道开始之前对封闭的命令进行完整的评估,在这种情况下,整个文件内容作为字符串数组获取,然后将该数组馈送到管道中。

与存储在临时变量中基本相同:

$lines = Get-Content C:\somepath\Setup.csproj
$lines | Select-String ......

【讨论】:

    【解决方案2】:

    你能不能试试这个:

    $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"  ;
    

    用一个文件在本地测试。

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 2019-01-24
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多