簡體   English   中英

如何使用XML文件中的PowerShell更新數據源連接字符串

[英]How to update the Data Source connection string using PowerShell in the XML file

我正在嘗試使用PowerShell使用新值自動更新web.config文件中的數據源。

這是我的連接字符串:

<connectionStrings>
    <add name="abcLogging" connectionString="Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" providerName="System.Data.SqlClient" />
</connectionStrings>

PowerShell腳本:

$newstring = '"Data Source=(test)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" '
$oldstring = '"Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" '
$XmlDocument = [xml](Get-Content "D:\abc\Web.config");
$value = $XmlDocument.configuration.connectionStrings.add.connectionstring 
$value = $value -replace "$oldstring","$newstring" | Set-Content -PassThru 

運行上面的腳本時出現以下錯誤。

The regular expression pattern "Data Source=(local)\abc; Trusted_Connection=True;
Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB"  is not valid.
At line:5 char:1
+ $value = $value -replace "$oldstring","$newstring" | Set-Content -Pas ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ("Data Source=(l...og=OnityLogDB" :String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

歡迎來到StackOverflow,Hari Krishna! 您的腳本會發生一些事情。

  1. 您的舊字符串和新字符串中的引號太多 - 將找不到舊字符串。 通常,應使用單引號,除非嵌入的$variableName要使用其值進行擴展。

  2. 括號被視為正則表達式特殊字符,因為您使用的是-replace語法。 [string]對象的.Replace方法可用於沒有正則表達式的簡單替換。

  3. Set-Content命令不知道要處理的文件。 但是你真的不想將文件的內容設置為$value 這樣可以獲得一個既沒有XML內容也沒有連接字符串的文件。

這是一個應該做你想要的腳本:

$configFile = 'C:\temp\web.config'

Set-Content -Path $configFile -Value @"
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
    <add name="abcLogging" connectionString="Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
"@

$newstring = 'Data Source=(test)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB'
$oldstring = 'Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB'

$XmlDocument = [xml](Get-Content $configFile);
$XmlDocument.configuration.connectionStrings.add | %{
    If($_.connectionString -eq $oldstring){
        $_.connectionString = $newstring
    }
}
$XmlDocument.Save($configFile)
Get-Content -Path $configFile

編輯:在其他測試期間發現更正的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM