bestsource

PowerShell로 App.config 설정을 읽고 쓰는 방법은 무엇입니까?

bestsource 2023. 10. 1. 21:07
반응형

PowerShell로 App.config 설정을 읽고 쓰는 방법은 무엇입니까?

테스트 환경에 구축하는 동안 자동 빌드 프로세스의 일부로 PowerShell을 사용하여 App.config 파일을 업데이트하고자 합니다.이거 어떻게 해요?

(로빈의 app.config를 기반으로) 코드는 훨씬 더 짧을 수 있습니다.

$appConfig = [xml](cat D:\temp\App.config)
$appConfig.configuration.connectionStrings.add | foreach {
    $_.connectionString = "your connection string"
}

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

이 샘플 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>

언급URL : https://stackoverflow.com/questions/871549/how-do-i-read-write-app-config-settings-with-powershell

반응형