【问题标题】:How to add-attribute if it doesn't exist using PowerShell?如果使用 PowerShell 不存在,如何添加属性?
【发布时间】:2015-07-23 06:36:33
【问题描述】:

在 web.config 文件中,如果 httpGetEnabledhttpsGetEnabled 属性不存在,我必须启用它们。

$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
    }

我能够使用 PowerShell 设置和获取属性值,但我不知道如何使用 PowerShell添加新属性。使用Get-help 添加属性没有帮助。如何使用 PowerShell 添加新属性?

【问题讨论】:

    标签: xml powershell xpath powershell-2.0


    【解决方案1】:

    我不知道您从哪里获得这些 XML cmdlet,但将 XmlDocument 保存在内存中会更容易(并且推荐),

    $xml = [xml] (Get-Content $Path)
    $node = $xml.SelectSingleNode($XPath)
    ...
    

    您也不需要对简单路径使用 XPath。树中的元素可以像对象一样被访问。

    $httpGetEnabled = $xml.serviceMetadata.httpGetEnabled
    

    无论如何,要添加属性:

    function Add-XMLAttribute([System.Xml.XmlNode] $Node, $Name, $Value)
    {
      $attrib = $Node.OwnerDocument.CreateAttribute($Name)
      $attrib.Value = $Value
      $node.Attributes.Append($attrib)
    }
    

    要保存文件,请使用$xml.Save($Path)

    【讨论】:

    • 知道为什么节点必须附加并设置属性吗?
    • 为澄清而编辑。 SetAttribute 只是设置属性的值。现在更清楚了,我在 Append 之前使用了$attrib.Value = $Value
    • 谢谢,我不确定这是否是一个 powershell 怪癖。
    【解决方案2】:

    在 PowerShellCore 6.2 上,我可以添加这样的属性。

    应该适用于任何 PowerShell 版本。

    [xml]$xml = gc my.xml
    $xml.element1.element2["element3"].SetAttribute("name", "value")
    

    这是因为在 XmlElement 上使用包装器属性返回包装值时,使用索引运算符返回一个纯 Xml 对象。原生的“SetAttribute”如果不存在就会创建一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2022-01-06
      相关资源
      最近更新 更多