getting app.config elements in powershell

佐手、 提交于 2019-12-12 17:27:44

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15939218/getting-app-config-elements-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!