Reputation: 51
Newbie to Powershell. I'd like to parse multiple files one after another. In order to do this, I need to load the files as a XML. This is my code so far:
for ($i=0; $i -le 5; $i++)
{
$contents = Get-ChildItem -Path $path -Force -Recurse
File |Select-Object -First $i | Select-Object -Last 1
$fl = $contents.Name
$xml.Load(".\downloads\Test\$fl")
}
If I remove for ($i=0; $i -le 5; $i++)
it works. But I need it to work with the for loop. Any ideas?
Upvotes: 0
Views: 459
Reputation: 8367
Assuming you'd like to actually pull data out of the files, I'd recommend using Select-XML.
Select-XML lets you query with XPath, and will return the file, xpath, and node (this might be handy if you need to take the file name into account for any reason).
# get all .xml files beneath downloads\test
Get-ChildItem -LiteralPath '\downloads\Test' -filter *.xml |
Select-Xml -XPath . # Get the root node of each file
You can also get fairly specific with your -XPath:
$elementOfInterest = 'a'
# get all .xml files beneath downloads\test
Get-ChildItem -LiteralPath '\downloads\Test' -filter *.xml |
Select-Xml -XPath "//$elementOfInterest" # Get any element of interest
Upvotes: 0
Reputation: 51
Solved it with this code:
$files = Get-ChildItem -LiteralPath ".\downloads\Test"
$xml = New-Object System.Xml.XmlDocument
foreach ($file in $files)
{
$xml.Load($file.FullName)
}
This enabled me to acess and encode every file in the folder.
Upvotes: 1
Reputation: 1816
you could do:
$filepaths = (get-childitem -Path C:\tmp -Recurse -Filter '*.xml').psPath
#XML per cast
$xmldocuments = @(
$filepaths | %{
[xml](get-content -path $_)
}
)
Alternatively create a new xml object and use the load method
$xml = New-Object -TypeName xml
$xmldocuments = @(
$filepaths | %{
$xml.Load($_)
$xml
}
)
The Array xmlDocuments contains each xml document as element.
Upvotes: 2