XML to powershell array

12,059

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
}
Share:
12,059
Tobi123
Author by

Tobi123

Just here to get solutions and help others :)

Updated on June 26, 2022

Comments

  • Tobi123
    Tobi123 almost 2 years

    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.