Hi I am trying to change the values of a connection string for a web.config file but getting error:
The property
'connectionString'
cannot be found on this object. Verify that the property exists and can be set.
Here's the script I'm using:
$webConfig = 'C:\Users\test\Desktop\web\web.config'
$doc = (Get-Content $webConfig) -as [Xml]
$obj = $doc.configuration.appSettings.add | where {$_.Key -eq 'CommandTimeOut'}
$obj.value = '60'
$config = [xml](gc $webConfig)
$con= $config.configuration.connectionStrings.add|where-object{$_.name -eq "password"};
$con.connectionString = $con.connectionString -replace "123456", "admin1234"
$doc.Save($webConfig)
I've modified the code as below, but it's still not working and I'm getting the same error.
$cfg = [xml](gc $webConfig)
$con= $cfg.configuration.connectionStrings.add|where-object{$_.name -eq "password"};
$cfg.configuration.connectionStrings.add.connectionString=
$cfg.configuration.connectionStrings.add.connectionString -replace "123456","admin123"
$doc.Save($webConfig)
Late, but just in case someone may find a use for it, I've written a re-usable Power-Shell do to that.
#set the value of this to your own db config
$myConnectionString = "Data Source=.;Initial Catalog=<Database>;Integrated Security=True";
$webConfig = '.\Api\Web.config'
$dbUpConfig = '.\Database\App.config'
$unitTestConfig = '.\Test\App.config'
Function updateConfig($config)
{
$doc = (Get-Content $config) -as [Xml]
$root = $doc.get_DocumentElement();
$activeConnection = $root.connectionStrings.SelectNodes("add");
$activeConnection.SetAttribute("connectionString", $myConnectionString);
$doc.Save($config)
}
updateConfig($webConfig)
updateConfig($dbUpConfig)
updateConfig($unitTestConfig)
a dirty way could be to replace the text without parsing the xml, something like this (in case there is no previous connectionstrings defined ) :
$replacementstring=@"
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
"@
(gc c:\temp\web.config) -replace "<connectionStrings/>" ,$repl | out-file c:\temp\new_web.config
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With