请使用PowerShell脚本帮助我:
在Config-B.xml中删除特定的<Section Name="APILibraries">
节点。
从Config-A.xml中读取特定的<Section Name="APILibraries">
节点。
在config-B.xml中附加第2步的值。
代码块1&amp; 2工作正常。我能够读取该值以及从config-B.xml中删除该节点。但是,在代码块3中,PowerShell脚本的倒数第二行会抛出错误,因为它无法导入空节点。
以下是Config-A.xml,它是source,Config-B.xml是PowerShell脚本的目标。
Config-A.xml
:
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<Data>
<Section Name="APILibraries">
<Item Name="TIMSS.API.User" Layer="User" Type="Custom" RootNamespace="TIMSS.API.User" FileName="TIMSS.API.User.dll" />
<Item Name="TIMSS.API.User.Generated" Layer="User" Type="Generated" RootNamespace="TIMSS.API.User" FileName="Personify.API.User.Generated.dll" />
<Item Name="TIMSS.API.Base" Layer="Base" Type="Custom" RootNamespace="TIMSS.API.Base" FileName="TIMSS.API.Base.dll" />
<Item Name="TIMSS.API.Generated" Layer="Base" Type="Generated" RootNamespace="TIMSS.API.Generated" FileName="TIMSS.API.Generated.dll" />
<Item Name="TIMSS.API.Core" Layer="Core" Type="Custom" RootNamespace="TIMSS.API.Core" FileName="TIMSS.API.Core.dll" />
</Section>
</Data>
</Configuration>
Config-B.xml
:
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<Data>
<Section Name="APILibraries">
<Item Name="TIMSS.API.Base" Layer="Base" Type="Custom" RootNamespace="TIMSS.API.Base" FileName="TIMSS.API.Base.dll" />
<Item Name="TIMSS.API.Generated" Layer="Base" Type="Generated" RootNamespace="TIMSS.API.Generated" FileName="TIMSS.API.Generated.dll" />
<Item Name="TIMSS.API.Core" Layer="Core" Type="Custom" RootNamespace="TIMSS.API.Core" FileName="TIMSS.API.Core.dll" />
</Section>
</Data>
</Configuration>
PowerShell脚本:
###Code Block - 1 : Get Source XML <Section Name="APILibraries"> Node Value ###
$CustomWinClientConfigXmlSource = "SourcePath\Config.xml"
[xml]$SourceConfigXml = Get-Content -Path "$CustomWinClientConfigXmlSource" -Raw
$SourceXmlNode = $SourceConfigXml | Select-Xml -XPath "//Section[@Name='APILibraries']"
$SourceXmlOutput = Write-Output "$SourceXmlNode"
$SourceXMLNodeValue = "$SourceXmlOutput"
### Code Block - 2 : Get The Target XML <Section Name="APILibraries"> Node Value And Delete It ##
$WinClientConfigFiles = "Config.xml"
$CustomWinClientConfigXmlTarget = "TargetPath\$WinClientConfigFiles"
$Path = "$CustomWinClientConfigXmlTarget"
[Xml]$servicefactoryconfig = Get-Content -Path $Path -Raw
$old = $servicefactoryconfig.SelectSingleNode("/Configuration/Data/Section[@Name='APILibraries']")
$parent = $old.ParentNode
[void] $parent.RemoveChild($old)
### Code Block - 3 : Append The Target XML <Section Name="APILibraries"> With Source XML Node Value ##
try {
$newNode = [Xml] @"
$SourceXMLNodeValue
"@
} catch {
Write-Error -Message 'Ignoring The Error Message' -ErrorAction Ignore
}
[void] $parent.AppendChild($servicefactoryconfig.ImportNode($newNode.DocumentElement, $true))
$servicefactoryconfig.Save($path)