简体   繁体   English

使用Powershell更新多个连接字符串数据源

[英]Update mulitple connection string data sources with Powershell

So I'm following what seemed like a pretty straight-forward demo on the internet to update the data-source attribute on my SQL connection string. 因此,我正在跟踪互联网上似乎很简单的演示,以更新SQL连接字符串上的data-source属性。 However, this line originally threw the error below 但是,此行最初将错误抛出以下

$doc = (gc $file) -as [xml]

gc : Cannot find path 'C:\\Windows\\system32\\LVOAGT.exe.config' because it does not exist. gc:找不到路径'C:\\ Windows \\ system32 \\ LVOAGT.exe.config',因为它不存在。

Since I'm brand new to Powershell I removed the gc and the error went away... however now the $doc variable is blank. 因为我是Powershell的新手,所以我删除了gc ,错误消失了……但是现在$doc变量为空。 Any idea how to grab a config file and use the method below to just update the data source portion of my connection string? 任何想法如何获取配置文件并使用下面的方法仅更新我的连接字符串的data source部分?

#environment variables
$env = "DEV"                       #This will need to be changed from DEV / INT / QUA / PRD
$oldServer = "QUASQ03"          #This will need to be changed from DEV / INT / QUA / PRD

#file and folder variables
$directory = "D:\AMS"
$folders = @("AgentsMonetToDss")

#new database value
$newValue = "$env-AgentResources-AMS-SQL.CORP"

#pull config file and insert new database connection
foreach($folder in $folders)
{
    Write-Host "Updating app.config for $folder" -ForegroundColor Yellow
    $dir = Get-ChildItem $directory\$folder -Recurse
    $config = $dir  | where {$_.extension -eq ".config"}

    foreach($file in $config)
    {
        $doc = (gc $file) -as [xml]
        $root = $doc.get_DocumentElement();
        $newCon = $root.connectionStrings.add.connectionString.Replace("data source=$oldServer\sql08a", "data source=$newValue\sql08a")
        $root.connectionStrings.add.connectionString = $newCon
        $doc.Save($file)
    }
}

EDIT 编辑

Here is a screenshot of what's contained in the first iteration of the inner foreach loop in the $file variable. 这是$file变量中内部foreach循环的第一次迭代中包含的屏幕快照。 The information in the pop up is accurate (filename, directory) 弹出窗口中的信息正确(文件名,目录)

在此处输入图片说明

SECOND EDIT 第二编辑

So the following code below will update the connection string. 因此,以下代码将更新连接字符串。 However this line gives the error below. 但是,此行给出以下错误。

$root.connectionStrings.add.connectionString = $newCon

The property 'connectionString' cannot be found on this object. 在此对象上找不到属性“ connectionString”。 Verify that the property exists and can be set. 验证该属性存在并且可以设置。

    $doc = [xml](Get-Content $file.FullName)
    $root = $doc.get_DocumentElement();
    [string]$newCon = $root.connectionStrings.add.connectionString.Replace($oldServer, $newValue)
    $root.connectionStrings.add.connectionString = $newCon
    $doc.Save($file.FullName) 

THIRD EDIT 第三编辑

The error 'connectionString' cannot be found on this object appears to be because we have multiple connection strings in the <connectionStrings> node. 'connectionString' cannot be found on this object错误'connectionString' cannot be found on this object似乎是因为<connectionStrings>节点中有多个连接字符串。 If I remove one of the connection strings from the config then the script runs fine. 如果我从配置中删除连接字符串之一,则脚本可以正常运行。 So I guess the question is how do I update MULTIPLE connection strings using powershell? 所以我想问题是如何使用Powershell更新多个连接字符串? The issue seems to be these lines below 问题似乎是下面的这些行

$newCon = $root.connectionStrings.add.connectionString.Replace($oldServer, $newValue)
$root.connectionStrings.add.connectionString = $newCon

The first line will scour both connection strings and replace the value as is requested to do. 第一行将搜索两个连接字符串,并按要求替换该值。 However, since I have simply a long string in $newCon and I'm attempting to add to the connectionString property of $root there's a clash. 但是,由于我在$newCon仅包含一个长字符串,并且试图将其添加到$rootconnectionString属性中,因此会发生冲突。

It's ugly but it worked... 丑陋但行得通...

I eventually had to store the entire connection string in a variable and run a -contains check against the connectionString property. 我最终不得不将整个连接字符串存储在一个变量中,并对connectionString属性运行-contains检查。 Will leave this post open for awhile in case anyone has a much efficient solution. 如果有人有一个非常有效的解决方案,将暂时保留此职位。

#generated config connection strings
Write-Host "Updating config ConnectionString nodes" -ForegroundColor Green
foreach($folder in $folders)
{
    Write-Host "Updating config for $folder" -ForegroundColor Yellow
    $dir = Get-ChildItem $directory\$folder -Recurse 
    $config = $dir  | where {$_.extension -eq ".config"}

    foreach($file in $config)
    {       
        $doc = [xml](Get-Content $file.FullName) 
        $doc.configuration.connectionStrings.add |%{
            if($_.connectionString.ToLower() -contains $oldGenConn.ToLower()){
                $_.connectionString = $newGenConn
            }            
        }
        $doc.Save($file.FullName)
    }
} 

Assume your connection string in your .exe.config files are as follows: 假设您的.exe.config文件中的连接字符串如下所示:

  <connectionStrings>
    <add name="DbConnectionExternal" connectionString="DbConnectionExternal" />
    <add name="DbConnectionSecurity" connectionString="DbConnectionSecurity" />
    <add name="ErrorDb" connectionString="ErrorDb" />
    <add name="OracleConnection" connectionString="OracleConnection" />
  </connectionStrings> 

After executing the following script file, this connection string inside all the .exe.config files which exists inside your root folder of the given path will be updated to: 执行以下脚本文件后,给定路径的根文件夹中存在的所有.exe.config文件中的此连接字符串将更新为:

  <connectionStrings>
    <add name="DbConnectionExternal" connectionString="A" />
    <add name="DbConnectionSecurity" connectionString="B" />
    <add name="ErrorDb" connectionString="C" />
    <add name="OracleConnection" connectionString="D" />
  </connectionStrings> 

Script file: 脚本文件:

get-childitem "Include the file path of your root folder" -recurse | where {$_.Name -match ".exe.config"} | % {
         $appConfigFile = $_.FullName
    $appConfig = New-Object XML
    $appConfig.Load($appConfigFile)
    foreach($connectionString in $appConfig.configuration.connectionStrings.add){
            if($connectionString.name -eq 'DbConnectionExternal'){
        $connectionString.connectionString = 'A'
        }
            elseif($connectionString.name -eq 'DbConnectionSecurity'){
        $connectionString.connectionString = 'B'
        }
            elseif($connectionString.name -eq 'ErrorDb'){
        $connectionString.connectionString = 'C'
        }
            elseif($connectionString.name -eq 'OracleConnection'){
        $connectionString.connectionString = 'D'
        }
    }
    $appConfig.Save($appConfigFile)
    }

It works perfectly and this script will be very useful when you deploy your application in to a server. 它运行完美,当您将应用程序部署到服务器中时,此脚本将非常有用。 You do not need to update each and every config file one by one. 您不需要一个个地更新每个配置文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM