Reputation: 715
I am trying to generate HTML reports of data collected in Powershell. I want to eventually have the HTML link to more specific information about the different elements in the table. In particular, the first column contains names of Virtual Machines, but this isn't particularly important. I am attempting to replace the name value with a link.
for($i=1; $i -le $xml.table.tr.Count-1; $i++){
$xml.table.tr[$i].td[0].replace($xml.table.tr[$i].td[0],"<a href=`"http://stackoverflow.com`">myLink</a>")
}
$file = Join-Path C:\users\myname\Documents "VMSpecs.html"
ConvertTo-Html -Title "VM Specs" `
-CssUri C:\Users\myname\Documents\style.css `
-Body $($xml.InnerXml) | Out-file $file
Invoke-item $file
Based on the output, the value of $xml.table.tr[$i].td[0] is being replaced with the link information but not permanently. When the file is written to HTML the link information is nowhere to be found, and the original value is still held in the td el
So,big picture, I would like to know how to append a link into html -fragment at a particular location. Any samples or resources be much obliged.
Upvotes: 1
Views: 1766
Reputation: 3163
Both .Replace and -replace produce a new string. What you'll want to do is reassign the results:
for($i=1; $i -le $xml.table.tr.Count-1; $i++){
$xml.table.tr[$i].td[0] = $xml.table.tr[$i].td[0].replace($xml.table.tr[$i].td[0],"<a href=`"http://stackoverflow.com`">myLink</a>")
}
Although, in this particular case, there doesn't seem to be any need for the replace at all. Since you're replacing the entire content of the td, just directly assign it:
for($i=1; $i -le $xml.table.tr.Count-1; $i++){
$xml.table.tr[$i].td[0] = "<a href=`"http://stackoverflow.com`">myLink</a>"
}
I initially misread your question as being about replace, rather than assigning to a node. It looks like when you get a particular element as above, PowerShell is converting it to a string, so you're not actually updating the node. Try this instead:
for($i=1; $i -le $xml.table.tr.Count-1; $i++){
($xml.table.tr[$i].GetElementsByTagName("td") | Select-Object -First 1)."#text" = "<a href=`"http://stackoverflow.com`">myLink</a>"
}
The "#text" property may vary, I'm not sure. I did a test with a very simple HTML file, and by doing a Get-Member on each level of the resulting XML object, I found that that was the property I needed to update.
Hmmm ... okay, try this. Create a new XML element containing the link, and append it to the td element:
for($i=1; $i -le $xml.table.tr.Count-1; $i++){
$link = $xml.CreateElement("a")
$link.SetAttribute("href", "http://stackoverflow.com")
$link.InnerText = "myLink"
$xml.table.tr[$i].FirstChild."#text" = ""
$xml.table.tr[$i].FirstChild.AppendChild($link)
}
Upvotes: 1