【问题标题】:Parse XML File with PowerShell and if a value is found, copy file to a new location [duplicate]使用 PowerShell 解析 XML 文件,如果找到值,则将文件复制到新位置 [重复]
【发布时间】:2020-06-08 14:47:02
【问题描述】:

我有一个应用程序,它在软件中的事件生命周期内输出 XML 文件。我需要解析 XML 文件,一旦匹配某些文本,将文件移动到另一个文件夹

每个 XML 文件的文件名格式为:Event Owner (MEMS)、Year (2020) 和序列号 (00012345)。该软件将在整个活动期间多次写入相同的文件,因此我需要在采取任何行动之前查找特定项目。 如果可能的话,我更愿意在 PowerShell 中执行此操作。

我需要找到

 `<EventUnits>
      <Unit>
        <UnitCode>xxxxxxx></UnitCode>
</EventUnits>`

<EventDetails>
        <EventCompletedTime>YYYY-MM-DD HH:MM:SS</EventCompletedTime>
</EventDetails>

一旦 UnitCode 等于 4 个单元代码之一并且 EventCompleted 具有有效的日期和时间,文件将移动到不同的文件夹。

【问题讨论】:

标签: xml powershell


【解决方案1】:

您可以读取文件内容,告诉 powershell 您希望文件在摄取时为 xml。然后你就可以访问里面的对象了。例如:

# read in the file contents of xml file
[xml]$fileContents = Get-Content 'C:\my\file\path.xml'

# you should now be able to access the contents of the file using dot notation
Write-Host $fileContents.EventUnits.Unit.UnitCode
Write-Host $fileContents.EventDetails.EventCompletedTime

这个例子假设

  1. EventUnits 和 EventDetails 是顶级节点(不嵌套 在另一个 xml 节点内)
  2. 该文件绝对存在。如果 您不确定是否可以测试文件是否存在
  3. 文件绝对是 xml 格式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2011-03-10
    相关资源
    最近更新 更多