用于删除多个XML文件中的XML节点的Powershell脚本
我希望使用PowerShell脚本循环遍历目录中的所有.xml文件,并删除匹配的.xml节点。我还想保存原始.xml文件的副本 我有这行代码,可以一次更改一个文件。但是,我希望有一个脚本可以对文件夹中的所有.xml文件执行此操作用于删除多个XML文件中的XML节点的Powershell脚本,powershell,Powershell,我希望使用PowerShell脚本循环遍历目录中的所有.xml文件,并删除匹配的.xml节点。我还想保存原始.xml文件的副本 我有这行代码,可以一次更改一个文件。但是,我希望有一个脚本可以对文件夹中的所有.xml文件执行此操作 Get-Content \\network\path\file1.xml | Where-Object {$_ -notmatch '<NUGLET key="000000000000025"/>'} | Set-Content \\network\path
Get-Content \\network\path\file1.xml | Where-Object {$_ -notmatch '<NUGLET key="000000000000025"/>'} | Set-Content \\network\path\file1.new.xml
Get Content\\network\path\file1.xml | Where Object{$\u-notmatch'}| 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 ChildItem\\network\path\*.xml |
ForEach对象{
#加载文件内容,删除字符串
(获取内容$|其中对象{$|-notmatch'}
}
那么,为什么会出现以下错误
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
Get Content:找不到路径“C:\Users\username\Documents\file1.xml”,因为它不存在。
在C:\Users\username\Local\Temp\4a8c4fc2-9af6-4c35-ab40-99d88cf67a86.ps1:5字符:14
+(获取内容获取内容$
中的$
仅将文件名传递给获取内容
,而不是完整路径,导致获取内容
在当前目录中查找该文件
请改为尝试获取内容$\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}
}
Get ChildItem\\network\path\*.xml|
ForEach对象{
复制项$\.FullName((连接路径$\.Directory$\.BaseName)+“.orig”+$\.Extension)
(获取内容$\.fullname)|其中对象{$\-notmatch''设置内容$\.fullname}
}
这很有效。谢谢Nate!所以现在我唯一的问题是,我想在所有文件被替换之前创建一个备份。有没有办法将其集成到管道中…或者也许在修改它们之前编写一个新的管道来创建备份更好。您的foreach对象
可以执行复制-Item
在执行获取内容之前
。如果可能的话,我喜欢用正确的扩展名保存备份文件,以便程序仍然知道如何打开它们。如果希望复制项目$\ FullName((连接路径$\目录$\ BaseName)+“.orig”+$\扩展名),请将复制行更改为该行
谢谢Stanley。这正是我想要的。
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}
}