0

Suppose I have the following XML file, and I want to use PowerShell (version 1.0) to manipulate the XML file to get the value for Foo (in this sample, value I want to get is "Foo Value") and Goo (in this sample, value I want to get is "Goo Value"), any ideas how to implement?

$FooConfig = [xml](get-content .\Foo.exe.config -ErrorAction:stop)

<configuration>
 <appSettings>
    <add key="Foo" value="Foo Value" />
    <add key="Goo" value="Goo Value" />
 </appSettings>
</configuration>

thanks in advance, George

2 Answers 2

4

The XPath API is very alive under PowerShell (your XML is, after all, just .NET objects), and it can often be the easiest to use if you just want a value:

$appSettingsSection = $fooConfig.configuration.appSettings;
$goo = $appSettingsSection.SelectSingleNode("add[@key='Goo']");
$goo.Value

Or if you want to enumerate the add elements as a PowerShell collection (a bit more PowerShell'ish :-)

$appSettingsSection = $fooConfig.configuration.appSettings.add

Will print

key                                                         value
---                                                         -----
Foo                                                         Foo Value
Goo                                                         Goo Value

And of course, you can pipe that result to additional commands to do whatever processing you like.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool, my question is answered!
2

Yet annother approach using XPATH with the XML API is to use SelectNodes:

PS> $FooConfig .SelectNodes('//add')

key                                                         value
---                                                         -----
Foo                                                         Foo Value
Goo                                                         Goo Value

1 Comment

Careful there! This is a config file and most config files have many 'add' nodes. So this would grab the 'add' nodes in appSettings as well as connectionStrings and god only knows what else.

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.