[ACCEPTED]-How do I read/write App.config settings with PowerShell?-app-config

Accepted answer
Score: 34

Given this sample App.config: C:\Sample\App.config:

<?xml version="1.0" encoding="utf-8" ?>
        <add name="dbConnectionString" 
             connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>

The 3 following script, C:\Sample\Script.ps1, will 2 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
# 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

Execute the script:

PS C:\Sample> .\Script.ps1


name: dbConnectionString  
connectionString: Data Source=(local);Initial Catalog=Northwind;Integrated Security=True

Updated 1 C:\Sample\App.config:

<?xml version="1.0" encoding="utf-8"?>
    <add name="dbConnectionString" 
         connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" />
Score: 34

The code can be much more shorter (based 1 on Robin's app.config):

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


More Related questions