2017-02-24 66 views
0

我用下面的命令工作: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" />任何行。

然而,當我運行上面的命令,我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-內容,並選擇串上述方法,然後再調用出文件對同一文件的方法嗎?

(注意,我從這個question上面的例子)。

+1

'(得到內容C:\ somepath \ Setup.csproj)' – PetSerAl

+0

@PetSerAl和wOxxOM - 這是它!學到了新的東西。如果您發佈答案,我會接受! – Vaccano

回答

0

能否請您試試這個:

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

經測試,在當地有一個文件。

2

該管道轉移個別項目,而不是等待前一命令的整個輸出被累積,因此,管道中的每個部分的begin { }塊在其創建初始化。在你的情況下,輸出文件流在實際處理開始之前被創建,從而覆蓋輸入。

括在括號中的命令:

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

它流水線開始前強制封閉命令的完整的評價,在這種情況下,整個文件的內容被提取爲字符串數組,然後這個陣列被饋送進入管道。

它基本上等同於一個臨時變量存儲:

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