Подтвердить что ты не робот

Как читать/записывать настройки App.config с помощью PowerShell?

Я хотел бы использовать PowerShell как часть нашего процесса автоматической сборки для обновления файла App.config при развертывании в нашей тестовой среде. Как я могу это сделать?

4b9b3361

Ответ 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>

Следующий script, 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)

Выполните команду script:

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")