Sam*_*abu 3 xml powershell xpath powershell-2.0
在web.config文件中httpGetEnabled,httpsGetEnabled如果它们不存在,我必须启用和属性.
$Path = "c:\web.config"
$XPath = "/configuration/system.serviceModel/behaviors/serviceBehaviors/behavior"
if ( Select-XML -Path $Path -Xpath $XPath ) {
"Path available"
$attributePath = $Xpath +="/serviceMetadata"
"Attribute path is $attributePath"
If (Get-XMLAttribute -Path $Path -Xpath $attributePath -attribute "httpGetEnabled" ) {
"httpGetEnabled is present"
}
ElseIf (Get-XMLAttribute -Path $Path -Xpath $attributePath -attribute "httpsGetEnabled") {
"httpsGetEnabled is present"
}
Else {
"Add both httpGetEnabled and httpsGetEnabled attribute with the value true and false accordingly"
$attributeset = @" httpGetEnabled="false" "@
New-Attribute -path $path -xpath $XPath -attributeset $attributeset
}
Run Code Online (Sandbox Code Playgroud)
我可以使用PowerShell设置和获取属性值,但我不知道如何使用PowerShell 添加新属性.没有可Get-help用于添加属性的帮助.如何使用PowerShell添加新属性?
我不知道你从哪里获得这些XML cmdlet,但是将XmlDocument保存在内存中要容易得多(并且推荐),
$xml = [xml] (Get-Content $Path)
$node = $xml.SelectSingleNode($XPath)
...
Run Code Online (Sandbox Code Playgroud)
您也不需要将XPath用于简单路径.可以像对象一样访问树中的元素.
$httpGetEnabled = $xml.serviceMetadata.httpGetEnabled
Run Code Online (Sandbox Code Playgroud)
无论如何,要添加属性:
function Add-XMLAttribute([System.Xml.XmlNode] $Node, $Name, $Value)
{
$attrib = $Node.OwnerDocument.CreateAttribute($Name)
$attrib.Value = $Value
$node.Attributes.Append($attrib)
}
Run Code Online (Sandbox Code Playgroud)
要保存文件,请使用 $xml.Save($Path)
在 PowerShellCore 6.2 上,我可以添加这样的属性。
应该适用于任何 PowerShell 版本。
[xml]$xml = gc my.xml
$xml.element1.element2["element3"].SetAttribute("name", "value")
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为在 XmlElement 上使用包装器属性返回包装值时,使用索引运算符返回一个纯 Xml 对象。如果不存在,本机“SetAttribute”将创建一个。
| 归档时间: |
|
| 查看次数: |
12980 次 |
| 最近记录: |