[英]How to navigate to and change value in XML config file with Powershell?
我試圖在以下XML 中將 Value UseFunction="false" Value="Production"更改為Value UseFunction="false" Value="Training" :
<?xml version="1.0" encoding="utf-8"?>
<ParametersInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ParameterGroup TestRequired="false" Name="CommonSystemConfig" xmlns="http://www....">
<Parameter Name="DefaultEnvironmentId" Text="DefaultEnvironmentId" ParameterType="List">
<Value UseFunction="false" Value="Production">
<ValueList>
<string>Production</string>
<string>Training</string>
<string>Staging</string>
</ValueList>
</Value>
<AutoSetValue UseFunction="false" Value="Production" />
<IsUppercaseInput>false</IsUppercaseInput>
<Description>The value can only be "Production" or "Training" or "Staging"</Description>
<IsSetSuccessfully>true</IsSetSuccessfully>
<Visible Type="0" Value="True" />
<IsReadOnly Type="0" Value="False" />
<AllowEmpty Type="0" Value="True" />
</Parameter>
u/Mathias R 為我提供了一個腳本。 Jessen,但后來我注意到我在帖子中犯了一些錯誤,不得不刪除它。 這是我現在所在的位置,但目標 XML 文件中的值沒有更改:
# load xml document from disk
$xmlFilePath = 'c:\Userdata\ParamBkUp.xml'
$rootedPath = Convert-Path $xmlFilePath
$xmlDoc = [xml]::new()
$xmlDoc.Load($rootedPath)
$nodesToChange = $xmlDoc |Select-Xml -XPath '//ParametersInfo/ParameterGroup[@Name="CommonSystemConfig"]/Parameter[@Name="DefaultEnvironmentId"]/Value[@Value="Production"]'
foreach($result in $nodesToChange){
# update the Value attribute on the discovered `Value` nodes
$result.Node.SetAttribute('Value', 'SomeOtherEnvironmentName')
}
# save changes to disk
$xmlDoc.Save($rootedPath)
我解決了以前發布的問題,但它已關閉。 這是 PowerShell 和 xml linq 的解決方案
using assembly System
using assembly System.Linq
using assembly System.Xml.Linq
$Filename = "c:\temp\test.xml"
$xDoc = [System.Xml.Linq.XDocument]::Load($Filename)
$descendants = $xDoc.Descendants()
$AutoSetValue = [System.Linq.Enumerable]::Where($descendants, [Func[object,bool]]{ param($x) $x.Name.LocalName -eq "AutoSetValue"})
Write-Host "AutoSetValue = " $AutoSetValue
$AutoSetValue.SetAttributeValue("Value","Training")
Write-Host "AutoSetValue = " $AutoSetValue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.