如何使用PowerShell读取/写入App.config设置? [英] How do I read/write App.config settings with PowerShell?

查看:273
本文介绍了如何使用PowerShell读取/写入App.config设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将PowerShell用作我们自动构建过程的一部分,以在部署到我们的测试环境中时更新App.config文件.我该怎么办?

I'd like to use PowerShell as part of our automated build process to update an App.config file while deploying into our test environment. How can I do this?

推荐答案

给出此示例App.config:C:\ Sample \ App.config:

Given this sample 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将读取和写入设置:

The following script, C:\Sample\Script.ps1, will read and write a setting:

# 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:

Updated 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>

这篇关于如何使用PowerShell读取/写入App.config设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆