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

前端 未结 4 1786
一向
一向 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:20

    Hey, I have come up with another answer which I like better. This one doesn't rely on the browser supporting 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
    

    Is there a special badge for stealing the "marked as answer" from yourself? ;-)

提交回复
热议问题