【发布时间】:2015-03-13 18:15:36
【问题描述】:
所以我正在关注互联网上看似非常简单的演示,以更新我的 SQL 连接字符串上的 data-source 属性。但是,这行最初抛出了下面的错误
$doc = (gc $file) -as [xml]
gc : 找不到路径“C:\Windows\system32\LVOAGT.exe.config”,因为它不存在。
由于我是 Powershell 的新手,我删除了 gc 并且错误消失了......但是现在 $doc 变量为空白。知道如何获取配置文件并使用下面的方法来更新我的连接字符串的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)
}
}
编辑
这是$file 变量中内部foreach 循环的第一次迭代中包含的屏幕截图。弹出的信息准确无误(文件名、目录)
第二次编辑
所以下面的代码将更新连接字符串。然而,这一行给出了下面的错误。
$root.connectionStrings.add.connectionString = $newCon
在此对象上找不到属性“connectionString”。验证该属性是否存在并且可以设置。
$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)
第三次编辑
错误'connectionString' cannot be found on this object 似乎是因为我们在<connectionStrings> 节点中有多个连接字符串。如果我从配置中删除其中一个连接字符串,则脚本运行良好。所以我想问题是如何使用 powershell 更新多个连接字符串?问题似乎是下面的这些行
$newCon = $root.connectionStrings.add.connectionString.Replace($oldServer, $newValue)
$root.connectionStrings.add.connectionString = $newCon
第一行将搜索两个连接字符串并按照要求替换值。但是,由于我在$newCon 中只有一个长字符串,并且我试图添加到$root 的connectionString 属性中,因此存在冲突。
【问题讨论】:
-
它不应该来自
Windows\system32。更新了帖子。 -
我已经在
$directory\$folder上致电Get-ChildItem。那部分正在做它应该做的事情(我可以看到该目录中的所有文件)。 -
@user2864740 使用来自调试会话的信息更新了帖子
-
我认为应该是
(gc $file.FullName)。 -
谢谢,这让我摆脱了最初的错误。现在出现新错误...更新了帖子。
标签: xml powershell connection-string config