【问题标题】:Powershell script for deleting an XML node in multiple XML files用于删除多个 XML 文件中的 XML 节点的 Powershell 脚本
【发布时间】:2013-04-26 17:11:18
【问题描述】:

我想让 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} 
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    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} 
    }
    

    【讨论】:

    • 那行得通。谢谢内特!所以现在我唯一的问题是我想在所有文件被替换之前创建一个备份。有没有办法将它集成到管道中......或者也许最好在修改它们之前编写一个新管道来创建备份。
    • 您的foreach-object 可以在执行copy-item 之前执行get-content
    • 如果可能的话,我喜欢用正确的扩展名保存备份文件,这样程序仍然知道如何打开它们。如果您想要 Copy-Item $_.FullName ((Join-Path $_.Directory $_.BaseName) + ".orig" + $_.Extension ),请将您的复制行更改为此
    • 谢谢斯坦利。这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 2020-08-05
    • 2020-11-05
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2015-08-30
    • 2017-04-10
    相关资源
    最近更新 更多