简体   繁体   中英

Replacting XML node text using PowerShell

I am having my XML document as follows

  <Batch>
  <Alter>
    <ObjectDefinition>
      <DataSources>
        <DataSource>
          <ConnectionString>Provider=SQLNCLI11.1;Data Source=ABC;Integrated Security=SSPI;Initial Catalog =TesDB1</ConnectionString>
          <ConnectionString>Provider=SQLNCLI11.1;Data Source=XYZ;Integrated Security=SSPI;Initial Catalog =TesDB1</ConnectionString>
        </DataSource>
      </DataSources>
    </ObjectDefinition>
  </Alter>
</Batch>

I would like to replace the entire connection-string nodes as follows

$ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database"

Here is what I tried but this is replacing only one node content

$XMLA = "D:\employee.xml"
$SqlDataBase = [xml](Get-Content $XMLA)
$data = $SqlDataBase.SelectNodes("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString")
#$data
$DataSource = "localhost"
foreach($xn in $data)
{

   $DataBase = $xn.'#text'.Split(";").Split("=")
   $DataBase[$DataBase.Length - 1]
   $DataBase = $DataBase[$DataBase.Length - 1]

   $ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database"

   $SqlDataBase.SelectSingleNode("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString").InnerText = "$ConnectionString";
}
$SqlDataBase.Save($XMLA)

So any better way to replace multiple nodes please let me know

This is best way where I have taken the source from here

Selecet XML Nodes by similar names in Powershell

$XMLA = "D:\employee.xml"
$SqlDataBase = [xml](Get-Content $XMLA)
$data = $SqlDataBase.SelectNodes("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString")
#$data
$DataSource = "localhost"

$SqlDataBase.Batch.Alter.ObjectDefinition.DataSources.DataSource.ChildNodes | Where-Object Name -Match 'ConnectionString' | ForEach-Object {

    $DataBase = $_.'#text'.Split(";").Split("=")
    $DataBase = $DataBase[$DataBase.Length - 1]

    $ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database"

    $_.'#text' = "$ConnectionString"
}

$SqlDataBase.Save($XMLA)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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