代码之家  ›  专栏  ›  技术社区  ›  Robin

如何使用PowerShell读取/写入app.config设置?

  •  24
  • Robin  · 技术社区  · 17 年前

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

    2 回复  |  直到 17 年前
        1
  •  28
  •   Robin    17 年前

    给定此示例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
  •  25
  •   Shay Levy    17 年前

    代码可以短得多(基于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")
    
    推荐文章