function Set-ConnectionString { <# .SYNOPSIS Sets a connection string in the specified config file. Filepath defaults to the 64 bit machine config. #> param ( [Parameter(Mandatory = $true)] [string]$name, [Parameter(Mandatory = $true)] [AllowEmptyString()] [string]$connectionString, [Parameter(Mandatory = $false)] [Alias("Path")] [string]$filePath = (Get-DotNetConfigPath -use64Bit $true), [Parameter(Mandatory = $false)] [string]$ComputerName = "localhost" ) $logLead = (Get-LogLeadName); # If a computername was provided, modify the filepath to be a UNC path. if((![string]::IsNullOrWhiteSpace($ComputerName)) -and ($ComputerName -ne "localhost")) { $filePath = (Get-UncPath -filePath $filePath -ComputerName $ComputerName); } if (!(Test-Path -PathType Leaf -Path $filePath)) { Write-Warning ("$logLead : Could not find a file at {0}. Execution cannot continue" -f $filePath); return $null; } Write-Verbose "$logLead : Reading Config file at $filePath"; $xml = Read-XMLFile $filePath; if(!$xml) { throw "$logLead : Config at $filePath could not be converted to xml."; } Write-Verbose "$logLead : Ensuring configuration and connectionStrings nodes exist.."; if(!$xml.configuration) { [void]$xml.AppendChild($xml.CreateNode("element","configuration", $null)) } if(!$xml.configuration.connectionStrings) { [void]$xml.SelectSingleNode("configuration").AppendChild($xml.CreateElement("connectionStrings")); } Write-Verbose "$logLead : Looking for an existing `"$name`" connection string." $connectionStrings = $xml.configuration.SelectSingleNode("connectionStrings"); $foundSetting = $false; $dirty = $false; if($connectionStrings.SelectNodes("add").count -gt 0) { $connectionNode = $connectionStrings.add | Where-Object { $_.Name -eq $name; } if($connectionNode) { $foundSetting = $true; if($connectionNode.connectionString -ne $connectionString) { Write-Host "$logLead : Found appSetting `"$name`", changing value from `"$($connectionNode.connectionString)`" to `"$connectionString`"."; $connectionNode.connectionString = $connectionString; $dirty = $true; } } } if(!$foundSetting) { Write-Host "$logLead : Could not find connection string name `"$name`". Creating one and setting value to `"$connectionString`"."; $connectionStringElement = $xml.CreateElement("add"); $connectionStringElement.SetAttribute("name", $name); $connectionStringElement.SetAttribute("connectionString", $connectionString); if($name -eq "AlkamiMaster") { $connectionStringElement.SetAttribute("providerName", "System.Data.SqlClient"); } [void]$connectionStrings.AppendChild($connectionStringElement); $dirty = $true; } if($dirty) { Write-Verbose "$logLead : Saving Config to path $filePath"; $xml.Save($filePath); } else { Write-Verbose "$logLead : No changes were made to $filePath" } }