PowerShell/XML-根据节点值将XML文件复制到文件夹



我是PowerShell的新手,但到目前为止,我使用它的能力有限。

所以,我的问题是:我有100000个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>

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

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

我想提前感谢大家,非常感谢你们能提供的任何帮助。

使用Select-Xml提取每个文档中的第一个<State>节点,然后在此基础上移动文件:

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

首先,您可以使用[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.
}

查找synax的Copy Item,了解如何将XML文件复制到各自的文件夹中。也可以随意使用上面的switch语句:(

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

最新更新