How to add-attribute if it doesn't exist using PowerShell?
Solution 1
I don't know where you're getting these XML cmdlets from, but it's much easier (and recommended) to just keep the XmlDocument in memory,
$xml = [xml] (Get-Content $Path)
$node = $xml.SelectSingleNode($XPath)
...
You also don't need to use XPath for simple paths. Elements in the tree can be accessed like objects.
$httpGetEnabled = $xml.serviceMetadata.httpGetEnabled
Anyway, to add the attribute:
function Add-XMLAttribute([System.Xml.XmlNode] $Node, $Name, $Value)
{
$attrib = $Node.OwnerDocument.CreateAttribute($Name)
$attrib.Value = $Value
$node.Attributes.Append($attrib)
}
To save the file back, use $xml.Save($Path)
Solution 2
On PowerShellCore 6.2 I am able to add attribute like this.
Should work on any PowerShell version.
[xml]$xml = gc my.xml
$xml.element1.element2["element3"].SetAttribute("name", "value")
This works because while using the wrapper properties on XmlElement returns wrapped values, Using the indexing operator returns a pure Xml object. The native "SetAttribute" will create one if it does not exist.
Samselvaprabu
I am mainly working as a Build and integrator. I am maintaining ESXi servers and doing little bit of Configuration management activities (Base Clearcase and clearcase UCM) as every build and integrator.
Updated on December 19, 2020Comments
-
Samselvaprabu over 3 years
In the web.config file I have to enable
httpGetEnabled
andhttpsGetEnabled
attributes if they don`t exist.$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 }
I am able to set and get attribute values using PowerShell but I don't know how to add a new attribute using PowerShell. There isno help available using
Get-help
for adding attributes. How to add a new attribute using PowerShell? -
StingyJack over 6 yearsAny idea why the node must have the attribute appended and also set?
-
makhdumi over 6 yearsEdited for clarification. The
SetAttribute
was just to set the value of the attribute. It's clearer now that I used$attrib.Value = $Value
before the Append. -
StingyJack over 6 yearsThanks, I wasn't sure if that was a powershell quirk or not.