Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML to powershell array

I want to load xml content into an array within a powershell script. Why dows this not work? :(

My XML:

<settings>
    <services>
       <sv>service1</sv>
       <sv>service2</sv>
    </services>
</settings>

My Powershell script. This seems to work, but I'm not sure

[xml]$xml = Get-Content "D:\config.xml"
[array]$service_arr = $xml.settings.services.sv

But now I want to display it, but I get "Cannot index into a null array."

$service_arr[0]

I don't really want to have a variable with a different generic name for each service. I only want to be able to address my services with array[0]...array[1] etc.

like image 492
Tobi123 Avatar asked Oct 15 '25 14:10

Tobi123


1 Answers

You don't have to cast $xml.settings.services.sv explicit to an [array], you can just iterate over it using for example a foreach loop:

foreach ($service in $xml.settings.services.sv)
{
    Write-host $service
}
like image 53
Martin Brandl Avatar answered Oct 18 '25 09:10

Martin Brandl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!