Page 1 of 1

Get data from multiple XML files

Posted: Sun Jan 27, 2019 1:09 pm
by Hal242
Hello, I have many XML files in a folder. Each XML file has a different name, but all have the same XML schema. I can get values from different nodes in any of the XML files using the following code;

Code: Select all

[xml]$xmlDocument = Get-Content -Path D:\TEMP\FileName1.xml
$xmlDocument.HardwareVerificationData.runtime.ChildNodes
$xmlDocument.HardwareVerificationData.Hardware.CPUID.ChildNodes
$xmlDocument.HardwareVerificationData.Hardware.SMBIOS.System.ChildNodes
$xmlDocument.HardwareVerificationData.Hardware.SMBIOS.System.p[4]
$xmlDocument.HardwareVerificationData.Hardware.SMBIOS.Baseboard.ChildNodes
$xmlDocument.HardwareVerificationData.Hardware.SMBIOS.Baseboard.p[4, 5]
	
etc...
The thing I cannot figure out is how to write code which will look at all of the files in my directory, say D:\temp instead of hardcoding the FileName1.xml in the first get-content command. I imagine I need to create some sort of loop to iterate through the folder and setup the get-content command to use a variable instead of the FileName1.xml and then loop through all of the files in the directory and use the dot notation similar to above to build out my report.

I am not familiar with XPath, and some searching I have done suggests that XPath is the old school way to do it (from what I can tell), but I am sure there is an easier way.

Any suggestions would be greatly appreciated.

Re: Get data from multiple XML files

Posted: Sun Jan 27, 2019 1:24 pm
by jvierra
Start with:

Help ForEach-Object -online

Example:

Code: Select all

Get-ChildItem *.xml |
     ForEach-Object{
           # process each file
           [xml]$xml = Get-Content $_
           …. other code     }
{/code]

Here are some PowerShell videos that will help you get started with PS and files.

https://youtu.be/6VK4TN6Umfk

Re: Get data from multiple XML files

Posted: Sun Jan 27, 2019 1:48 pm
by Hal242
thanks... I knew I was getting close and your reply helped me get to the solution.

this seems to do the trick;

Code: Select all

Get-ChildItem D:\temp -filter *.xml | ForEach-Object {
[xml]$xmlDocument = Get-Content -path d:\temp\$_
$xmlDocument.HardwareVerificationData.runtime.ChildNodes
$xmlDocument.HardwareVerificationData.Hardware.SMBIOS.Chassis.ChildNodes
}

Re: Get data from multiple XML files

Posted: Sun Jan 27, 2019 1:57 pm
by jvierra
You don't need to want to use a path structure. THe code I psoted is the correct wway to do this in PS. Whenyou learn more you will understand why.

Code: Select all

Get-ChildItem D:\temp\*.xml | 
    ForEach-Object {
        [xml]$xmlDocument = Get-Content $_
        $xmlDocument.HardwareVerificationData.runtime.ChildNodes
        $xmlDocument.HardwareVerificationData.Hardware.SMBIOS.Chassis.ChildNodes
    }