Home > Software engineering >  How to Extract string from XML Property
How to Extract string from XML Property

Time:05-20

Using powershell, I am attempting to extract the contents of Value="" which will either be Production or Training, from a XML file. Here is a snipit of the XML file:

<ParameterGroup TestRequired="false" Name="CommonSystemConfig" xmlns="http://www...">
    <Parameter Name="DefaultEnvironmentId" Text="DefaultEnvironmentId" ParameterType="List">
        <Value UseFunction="false" Value="Training">
            <ValueList>
                <string>Production</string>
                <string>Training</string>
                <string>Staging</string>

I currently have the script as follows:

$XMLfile = "\\$pchostname\$xmlPath"
[XML]$paramBackup = Get-Content $XMLfile

$paramBackup.ParametersInfo.ParameterGroup.parameter | Where-Object {$_.Name -eq 'DefaultEnvironmentId'} | Select-object -ExpandProperty 'Value'

The script is giving me:

UseFunction Value ValueList


false Production ValueList

How would I just output the Production or Training so that I could have it populate an xls with the corresponding computer hostname?

Thank you

CodePudding user response:

As you have it now, your object named Value has 3 properties, UseFunction,Value, and ValueList, and you need to select the child property named Value, which has a value of Training.

You could actually just duplicate what you already have, by adding another pipe and select to the end

| Select-Object -ExpandProperty 'Value'

So the full line would be

$paramBackup.ParametersInfo.ParameterGroup.parameter | Where-Object {$_.Name -eq 'DefaultEnvironmentId'} | Select-object -ExpandProperty 'Value' | Select-object -ExpandProperty 'Value'

Another way with additional dot-notation

($paramBackup.ParametersInfo.ParameterGroup.parameter | Where-Object {$_.Name -eq 'DefaultEnvironmentId'}).Value | Select-object -ExpandProperty 'Value'
  • Related