How to update app.config file using PowerShell?

Below code will help to update app.config file with given data-

#It helps to connect db and get the data.

$HostName = $env:computername
$connectionstring = 'Server=XX.XX.XX.XX;Database=TestDataBase;User Id=VM;Password=VMTest;MultipleActiveResultSets=True'
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = "SELECT [Params].value('(/root//Version/node())[1]', 'nvarchar(max)') as FirstName from Request where [Params].value('(/root//Name/node())[1]', 'nvarchar(max)') = '"+$HostName+"'"
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object “System.Data.DataTable”
$table.Load($result)
$Unified = $table | %{ $_.FirstName }

#It helps to update app.config file with given data.

$appConfigFile = 'C:\Project\ProjectPath\Project.dll.config'
$doc = (Get-Content $appConfigFile) -as [Xml]
$node = $doc.configuration.appSettings.add | where {$_.Key -eq 'Version'}
$node.value = $Unified
$doc.Save($appConfigFile)

Advertisements