【问题标题】:How do I read/write App.config settings with PowerShell?如何使用 PowerShell 读取/写入 App.config 设置?
【发布时间】:2010-10-26 16:08:28
【问题描述】:

我想在我们的自动构建过程中使用 PowerShell 来更新 App.config 文件,同时部署到我们的测试环境中。我该怎么做?

【问题讨论】:

    标签: powershell app-config


    【解决方案1】:

    鉴于此示例 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>
    

    【讨论】:

      【解决方案2】:

      代码可以更短(基于 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")
      

      【讨论】:

      • 酷,感谢您的提示。我没有意识到我可以使用那种语法。
      • 如果我们追求short,foreach应该写成%。
      • @Shay Levy 是否可以在配置文件中更新 ?像 这样的接缝我需要在每个 deployemnet 上更新这个值。你能帮我吗
      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 2013-01-09
      • 1970-01-01
      • 2011-05-12
      • 2012-12-02
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      相关资源
      最近更新 更多