Loop through XML files powershell
10,191
Solution 1
If your XML looks like this <doc><foo name='fooname'><bar>bar content</bar></foo></doc>
you access the content like so:
$MyXml = [xml](Get-Content $xmlFile)
$MyXml.doc.foo.name
$MyXml.doc.foo.bar
Solution 2
Try the following:
function list-xml-files() {
get-childitem -recurse -force | ? { -not $_.psisdirectory } | ? { $_.name.endswith('.xml') }
}
function list-data([xml]$xml) {
$path = $xml.ExportedContentItem.path
$name = $xml.ExportedContentItem.name
$ID = $xml.ExportedContentItem.ID
[string]::Format("{0}/{1} > {2}", $path, $name, $ID)
}
list-xml-files | % { [xml](get-content $_) } | ? { $_.ExportedContentItem } | % { list-data $_ }
This code follows a more functional style of programming. '%' is a map
, '?' is a filter
.
It showcases several nice features of PowerShell. You might want to install PowerShell 3.0 (you need .NET 4.0 as well) and you will be able to explore the various PowerShell features via IntelliSense.
Author by
Peck3277
Updated on June 15, 2022Comments
-
Peck3277 almost 2 years
I am trying to extract some content from XML files. I have what I need working for one file but I need to do it for all files in a directory. So far what I have is:
$files = Get-ChildItem C:\Users\rasuser\Desktop\import *.xml -recurse foreach ($file in $files){ $MyXml = [xml](Get-Content $file) #$path = $file.ExportedContentItem.path #$name = $file.ExportedContentItem.name #$GUID = $file.ExportedContentItem.ID #$path + "/" + $name + " > "+$GUID }
I'm not really understanding how to import read in the content to an XML format. Can anyone help me out?