Manish Nagar
Manish Nagar

Reputation: 13

How to get content of XML files using foreach loop in PowerShell?

I want to display the content of all the XML files present in a folder one by one. Commands I am using are:

$test = Get-ChildItem | Select-Object -Property Name
foreach ($i in $test) {
    Get-Content $i
}

but it is not working as expected. It is throwing an error saying:

Cannot find path \<dir_path>\@{Name=<filename>.xml} because it does not exist

Upvotes: 0

Views: 563

Answers (1)

HerbM
HerbM

Reputation: 571

Get-Content is wildcard aware so you can display them with simply:

Get-Content *.xml

If you want to perform a more complex action or perhaps separate them you could use something like:

Get-ChildItem *.xml -file | ForEach-Object { 
  Write-Warning ("`n    $($_.FullName) `n" + '=' * 72)
  Get-Content $_.fullName
}

This is just an example of what you might do to separate the files visually or perform any other action -- you could stop and wait for a keypress etc....

Upvotes: 3

Related Questions