config file which looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Environment" value="Dev Environment"/>
</appSettings>
</configuration>
How can i get the value of key "Environment" in Powershell? I mean it should return "Dev Environment" when you select key "Environment".
I prefer linq to use here anyone with any idea really appreciate that.
I recommend xpath.
First create an XmlDocument object like this:
$xml = [xml] @'
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Environment" value="Dev Environment"/>
</appSettings>
</configuration>
'@
... or this:
$xml = [xml] (Get-Content C:\file.xml)
Then use the SelectNodes or SelectSingleNode method and provide your xpath as an argument. xpath is domain specific language and can get somewhat complicated. This xpath query says give me the attribue named value of all nodes named add that have an attribute named key with the value of Environment.
$xml.SelectNodes('//add[@key="Environment"]/@value')[0].'#text'
PowerShell adds a #text
NoteProperty on XmlElement and XmlAttribute objects you can use to access the text of the node.