2013-04-26 71 views
0

我想讓PowerShell腳本循環遍歷目錄中的所有.xml文件並刪除匹配的.xml節點。我也想保存原始.xml文件的副本。用於刪除多個XML文件中的XML節點的Powershell腳本

我有這行代碼,它可以一次更改一個文件。不過,我想要一個腳本來處理文件夾中的所有.xml文件。

Get-Content \\network\path\file1.xml | Where-Object {$_ -notmatch '<NUGLET key="000000000000025"/>'} | Set-Content \\network\path\file1.new.xml 

我一直對這個劇本,但我在那裏似乎是在尋找我的文檔目錄,而不是在網絡路徑中的一個點。

Get-ChildItem \\network\path\ *.xml | 
ForEach-Object { 
# Load the file's contents, delete string 
(Get-Content $_) | Where-Object {$_ -notmatch '<NUGLET key="000000000000025"/>'} 
} 

那麼,爲什麼我會得到以下錯誤?

Get-Content : Cannot find path 'C:\Users\username\Documents\file1.xml' because it does not exist. 
At C:\Users\username\Local\Temp\4a8c4fc2-9af6-4c35-ab40-99d88cf67a86.ps1:5 char:14 
+  (Get-Content <<<< $_) | Where-Object {$_ -notmatch '<NUGLET key="000000000000025"/>'} 
+ CategoryInfo   : ObjectNotFound: (C:\Users\userna...-file1.xml:String) [Get-Content], ItemNotFoundException 
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand 

而我該如何修改腳本來製作原始xml文件的備份副本。

編輯:

和Nate的建議

所以,現在我使用的是以下幾點:

Get-ChildItem \\network\path\ *.xml | 
ForEach-Object { 
# Load the file's contents, delete string 
(Get-Content $_.fullname) | Where-Object {$_ -notmatch '<NUGLET key="000000000000025"/>' | Set-Content $_.fullname} 
} 

回答

2

Get-Content $_$_只有在通過文件的Get-Content,而不是完整的路徑,造成Get-Content在當前目錄中查找它。

改爲嘗試Get-Content $_.FullName


完整的腳本,其中包括複製文件,會是這樣的:

Get-ChildItem \\network\path\ *.xml | 
ForEach-Object { 
    Copy-Item $_.FullName ((Join-Path $_.Directory $_.BaseName) + ".orig" + $_.Extension) 
    (Get-Content $_.fullname) | Where-Object {$_ -notmatch '<NUGLET key="000000000000025"/>' | Set-Content $_.fullname} 
} 
+0

工程。謝謝Nate!所以現在我唯一的問題是我想在替換之前創建所有文件的備份。有沒有辦法將它集成到管道中......或許也許最好是在修改它們之前編寫新的管道來創建備份。 – 2013-04-26 18:09:38

+0

您的'foreach-object'可以在執行'get-content'之前執行'copy-item'。 – 2013-04-26 18:13:02

+1

我喜歡用適當的擴展名保存備份文件,如果可能的話,程序仍然知道如何打開它們。如果你需要'Copy-Item $ _。FullName((Join-Path $ _。Directory $ _。BaseName)+「.orig」+ $ _。Extension)' – 2013-04-26 18:45:55