4

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.

3
  • 1
    don't cast to array, use $xml.settings.services.sv[0] and $xml.settings.services.sv[1] Commented Jul 27, 2015 at 12:46
  • This doesn't solve my problem, because my powershell script does not know how many elements the service tag in the xml file includes. Commented Jul 27, 2015 at 12:49
  • 2
    use a foreach loop ^^ Commented Jul 27, 2015 at 12:52

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.