假设您想对 powershell 的某些表格输出进行一些奇特的格式化,目标是 html(用于网络服务器,或通过电子邮件发送)。例如,假设您希望某些数值具有不同的背景颜色。任何。我可以想到两种可靠的编程方式来实现这一点:输出 XML 并使用 XSLT 进行转换,或者输出 HTML 并使用 CSS 进行装饰。
XSLT 可能是两者中较难的一个(我这么说是因为我不知道),但据我所知,它的好处是能够为上述花哨的选择嵌入选择标准(xpath?)格式化。另一方面,CSS 需要帮助。如果您希望对某个单元格进行特殊处理,那么您需要使用类、id 或类似的东西将它与它的 sibling 区分开来。 PowerShell 本身并没有真正做到这一点的方法,因此这意味着在 HTML 离开 convertto-html 时解析 HTML 并添加例如“强调”类:
<td class="emphasis">32MB</td>
我不喜欢所需的文本解析的想法,特别是考虑到我宁愿能够在 Powershell 命中 HTML 之前以某种方式强调需要强调的内容。
XSLT 是最好的方法吗?对离开 convertto-html 后如何标记 HTML 有任何建议或不同方式的想法?
最佳答案
嘿,我想出了另一个我更喜欢的答案。这个不依赖于支持 JavaScript 的浏览器 ...
Add-Type -AssemblyName System.Xml.Linq
# Get the running processes to x(ht)ml
$xml = [System.Xml.Linq.XDocument]::Parse( "$(Get-Process | ConvertTo-Html)" )
# Find the index of the column you want to format:
$wsIndex = (($xml.Descendants("{http://www.w3.org/1999/xhtml}th") | Where-Object { $_.Value -eq "WS" }).NodesBeforeSelf() | Measure-Object).Count
# Format the column based on whatever rules you have:
switch($xml.Descendants("{http://www.w3.org/1999/xhtml}td") | Where { ($_.NodesBeforeSelf() | Measure).Count -eq $wsIndex } ) {
{200MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: red;"); continue }
{20MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: orange;"); continue }
{10MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: yellow;"); continue }
}
# Save the html out to a file
$xml.Save("$pwd/procs2.html")
# Open the thing in your browser to see what we've wrought
ii .\procs2.html
是否有一个特殊的徽章可以从你自己那里窃取“标记为答案”? ;-)
关于html - 在 PowerShell 管道中有选择地格式化数据并输出为 HTML 的技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4559233/