visual-studio-2010 - 在 powershell 中获取 app.config 元素

标签 visual-studio-2010 powershell linq-to-xml

配置文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
    <add key="Environment" value="Dev Environment"/>
</appSettings>
</configuration>

如何在 Powershell 中获取“Environment”键的值?我的意思是,当您选择“环境”键时,它应该返回“开发环境”。

我更喜欢在这里使用 linq,任何有想法的人都非常感激。

最佳答案

我推荐xpath .

首先创建一个XmlDocument像这样的对象:

$xml = [xml] @'
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
    <add key="Environment" value="Dev Environment"/>
</appSettings>
</configuration>
'@

...或者这个:

$xml = [xml] (Get-Content C:\file.xml)

然后使用 SelectNodes 或 SelectSingleNode 方法并提供您的 xpath 作为参数。 xpath 是特定于领域的语言,可能会变得有些复杂。此 xpath 查询表示给我所有名为 add 的节点的属性命名值,这些节点具有名为 key 的属性,其值为 Environment。

$xml.SelectNodes('//add[@key="Environment"]/@value')[0].'#text'

PowerShell 在 XmlElement 和 XmlAttribute 对象上添加了 #text NoteProperty,可用于访问节点的文本。

关于visual-studio-2010 - 在 powershell 中获取 app.config 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939218/

相关文章:

linq-to-xml - LINQ 中的动态 Xelement 查询

c# - C#入门,如何调试.NET 4.0 MVC3项目?

c# - 如何将示例项目导入 Microsoft Visual Studio 2010

powershell - 读主机具有多种颜色

如果之后抛出错误,则数组的 Powershell 写输出丢失

regex - 从文件名中删除某些字符串模式而不影响扩展名

c# - 使用 XDocument.Parse 时保留回车

c# - XmlDocument.Load(String filename) 和 XmlDocument.Load(FileStream fs) 之间的区别

c++ - 碰撞。 QObject::connect 在静态对象实例的构造函数中

c# - 错误 : unable to start debugging on the server