Powershell 的输出文件在从自身通过管道传输时会清除文件 [英] Powershell's out-file clears the file when piped from itself

查看:34
本文介绍了Powershell 的输出文件在从自身通过管道传输时会清除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令:

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

这个想法是删除 Setup.csproj 中包含文本 <None Include="packages.config"/> 的所有行.

The idea is to remove any lines in Setup.csproj that have the text <None Include="packages.config" />.

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

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).

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

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

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

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.

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

(注意,我从这个问题得到了上面的例子.)

(Note, I got the above example from this question.)

推荐答案

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

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.

将命令括在括号中:

(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 ......

这篇关于Powershell 的输出文件在从自身通过管道传输时会清除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆