如何使用PowerShell读写App.config配置设置?

29

我希望在我们的自动化构建过程中使用PowerShell来更新App.config文件,同时部署到测试环境。如何实现?

2个回答

35
代码可以更短 (基于Robin的app.config):
$appConfig = [xml](cat D:\temp\App.config)
$appConfig.configuration.connectionStrings.add | foreach {
    $_.connectionString = "your connection string"
}

$appConfig.Save("D:\temp\App.config")

3
谢谢你的提示。我之前没意识到我能使用那种语法。 - Robin
2
如果我们追求简短,foreach 应该写成 %。 - Tanveer Badar
@Shay Levy是否有可能更新config文件中的<appSettings>? 看起来像是<appSettings><add key="IsFirstRun" value="False" /></appSettings> 我需要在每次部署时更新此值。你能帮我吗? - Manu Padmanabhan

34

给定这个样例 App.config:C:\Sample\App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="dbConnectionString" 
             connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
    </connectionStrings>
</configuration>

下面的脚本,C:\Sample\Script.ps1,将读取并写入一个设置:

# get the directory of this script file
$currentDirectory = [IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path)
# get the full path and file name of the App.config file in the same directory as this script
$appConfigFile = [IO.Path]::Combine($currentDirectory, 'App.config')
# initialize the xml object
$appConfig = New-Object XML
# load the config file as an xml object
$appConfig.Load($appConfigFile)
# iterate over the settings
foreach($connectionString in $appConfig.configuration.connectionStrings.add)
{
    # write the name to the console
    'name: ' + $connectionString.name
    # write the connection string to the console
    'connectionString: ' + $connectionString.connectionString
    # change the connection string
    $connectionString.connectionString = 'Data Source=(local);Initial Catalog=MyDB;Integrated Security=True'
}
# save the updated config file
$appConfig.Save($appConfigFile)

执行脚本:

PS C:\Sample> .\Script.ps1

输出:

name: dbConnectionString  
connectionString: Data Source=(local);Initial Catalog=Northwind;Integrated Security=True

更新了 C:\Sample\App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="dbConnectionString" 
         connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" />
  </connectionStrings>
</configuration>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接