Technique for selectively formatting data in a PowerShell pipeline and output as HTML

前端 未结 4 1702
一向
一向 2021-02-02 04:25

Say that you want to do some fancy formatting of some tabular output from powershell, and the destination is to be html (either for a webserver, or to be sent in an email). Let\

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 05:28

    As a result of some github discussions, I've updated this for PowerShell 4/5/6 using the .where() method thus eliminating the dependency on the pipeline. The slow part is generating the HTML whereas the actual XML manipulation only takes ~200 ms.

    Add-Type -AssemblyName System.Xml.Linq
    
    # Get the running processes to x(ht)ml. This is *SLOW*.
    $xml = [System.Xml.Linq.XDocument]::Parse([string] (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{$_.Value -eq "WS" }.
            NodesBeforeSelf().
                Count
    
    # Format the column based on whatever rules you have:
    switch($xml.Descendants("{http://www.w3.org/1999/xhtml}td").Where{@($_.NodesBeforeSelf()).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
    

提交回复
热议问题