用于删除多个XML文件中的XML节点的Powershell脚本

时间:2013-04-26 17:11:19

标签: powershell

我希望PowerShell脚本循环遍历目录中的所有.xml文件,并删除匹配的.xml节点。我还想保存原始.xml文件的副本。

我有这行代码,可以一次更改一个文件。但是,我想有一个脚本为文件夹中的所有.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} 
}

1 个答案:

答案 0 :(得分: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} 
}