【问题标题】:PowerShell / XML - Copy xml file to folder according to node valuePowerShell / XML - 根据节点值将 xml 文件复制到文件夹
【发布时间】:2020-08-07 07:50:39
【问题描述】:

我对 PowerShell 还很陌生,但到目前为止我使用它的能力有限。

所以,这是我的问题: 我有 100,000 个 xml 文件,其中包含一个具有 State 值的节点。 我想使用 PowerShell 读取文件,然后将文件复制到各自的 State 文件夹中。我可以让文件夹已经创建或让 PS 脚本来做。两者都可以,但我想学习如何做到这两个方面 1. 将文件复制到特定文件夹和 2. 创建文件夹然后将文件复制到其中。

例子:

XML1

<Member>
  <LastName>LASTNAME1</LastName>
  <FirstName>FIRSTNAME1</FirstName>
  <AddressParent>
    <Address>
      <Type>HOME1</Type>
      <Address1>123 STREET</Address1>
      <State>FL</State>
    </Address>
  </AddressParent>
</Member>

XML2

<Member>
  <LastName>LASTNAME2</LastName>
  <FirstName>FIRSTNAME2</FirstName>
  <AddressParent>
    <Address>
      <Type>HOME1</Type>
      <Address1>234 STREET</Address1>
      <State>NY</State>
    </Address>
  </AddressParent>
</Member>

重申: 我想阅读单个文件夹中存在的文件。 根据&lt;State&gt;节点将文件复制到各自的State文件夹中。

此外,每个 XML 文件有超过 1 个 &lt;State&gt; 节点,因此我需要使用绝对路径(不确定这是否是正确的术语)。

我要提前感谢大家,非常感谢您提供的任何帮助。

【问题讨论】:

    标签: xml powershell file copy nodes


    【解决方案1】:

    使用Select-Xml 提取每个文档中的第一个&lt;State&gt; 节点,然后根据该节点移动文件:

    Get-ChildItem |Select-Xml -XPath '//State[1]' |ForEach-Object {
      $State = $_.Node.InnerText
    
      # Check to see if folder already exists, otherwise create it
      if(-not(Test-Path $State)){
        $null = mkdir $State
      }
    
      # Move the source file to the state folder
      Move-Item -LiteralPath $_.Path -Destination $State
    }
    

    XPath 谓词的意思是:

    //           # Anywhere in the node tree
      State      # Find a <State> node
           [1]   # Select the one at position 1
    

    【讨论】:

      【解决方案2】:

      首先,您可以使用 [XML] 类型加速器导入每个 XML 文件,如下所示:

      $GetXmlFolderPaths = (Get-ChildItem -Path "PathWhereAllXMLDataIs").FullName
      
      foreach($XmlPath in $GetXmlFolderPaths){
      
          [XML]$CurrentXMLData = Get-Content $XmlPath
          $CurrentState = $CurrentXMLData.Member.AddressParent.Address.State 
          if($CurrentState -eq "FL"){
              <#
                  Copy the data into the florida folder
              #>
          }elseif($CurrentState -eq "NY"){
              #Move to NY Folder
          }
      
          #etc etc.
      }
      

      查找 Copy-Item 以获取有关如何将 XML 文件复制到其各自文件夹的语法。也可以随意使用上面的 switch 语句:)

      您说每个 XML 可能有多个 State 标记是在同一节点内还是在不同节点内?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-07
        • 2017-03-14
        • 1970-01-01
        • 2011-11-15
        • 1970-01-01
        • 2021-04-22
        • 1970-01-01
        相关资源
        最近更新 更多