I am writing a PowerShell script to add a meta tag to the head section of a HTML file. The tag must be as follows: <meta name=”robots” content=”noindex, nofollow”>.
The general snippet below works for all attributes, except for attributes called name:
$newMeta = $doc.createElement("meta")
$newMeta.attributename = "attribute content"
So this works:
$newMeta = $doc.createElement("meta")
$newMeta.content = "noindex, nofollow"
But this does not:
$newMeta = $doc.createElement("meta")
$newMeta.name = "robots"
The name attribute is just ignored in the output.
How can I add an attribute called name to the output?
2
Answers
I see no more takers, so I will try to answer the question myself. From what I understand, it is not possible to set an attribute called "name" on an HTML element, either with SetAttribute() or with a property (object.attributename).
I managed to obtain the same effect with a workaround: I first create an attribute with a placeholder name, then replace the placeholder name with the string "name".
I am aware that is not an elegant solution, and I am somewhat ashamed of it, but it works. Maybe the following snippet can be of help to others.
Assuming that
$doc
is anXmlDocument
object, this is a case of PowerShell’s XML adapter having a conflict between theName
property on each xml node object, and thename
attribute you want to add to the document itself.Use the
SetAttribute()
method to unambiguously set an attribute value: