C# 、PowerShell (读取config文件)

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="a1" value="a1_result"/>
    <add key="a2" value="a2_result"/>
  </appSettings>
</configuration>

C#代码

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = @"D:\App.config"; ;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
string value = config.AppSettings.Settings["a1"].Value;

C#转PowerShell

$map=New-Object System.Configuration.ExeConfigurationFileMap
$map.ExeConfigFilename="D:\App.config"

### OpenMappedExeConfiguration 是静态函数
### [System.Configuration.ConfigurationUserLevel]::None 枚举

$configobj = [System.Configuration.ConfigurationManager]::OpenMappedExeConfiguration($map,[System.Configuration.ConfigurationUserLevel]::None)
$value = $configobj.AppSettings.Settings["a1"].Value
$Value

PowerShell 使用 XPath 读取

XPath 20分钟入门
https://www.bilibili.com/video/BV1mW411D7wC

Select-Xml -Path F:\test.config -XPath "//appSettings/add[starts-with(@key,'a1')]/@value" | select-Object -ExpandProperty "node" |select value #a1_result
Select-Xml -Path F:\test.config -XPath "//appSettings/add[contains(@key,'a1')]/@value" | select-Object -ExpandProperty "node" |select value    #a1_result
Select-Xml -Path F:\test.config -XPath "//appSettings/add[contains(@key,'a')][2]/@value" | select-Object -ExpandProperty "node" |select value  #a2_result
Select-Xml -Path F:\test.config -XPath "//appSettings/add[2]/@value" | select-Object -ExpandProperty "node" |select value  #a2_result
posted @ 2022-04-18 22:23  shenshu  阅读(212)  评论(0编辑  收藏  举报