August 23, 2015

PowerShell - Convert Output to HTML table

In this post we will see how to convert the output to HTML table. Lets review the script:
 
$headStyle = '
<style type="text/css">
   
    body{
        font:verdana;
        background-color:#01f0f0;
    }

    table{
        padding:5px;
        width:100%;
        border-collapse:collapse;
    }
   
    table th{
        padding:5px;
        background: #b131f3;
        border-width: 1px;
    }
   
    table td{
        padding:5px;
        border:#5625f4 1px solid;
    }

    table tr:nth-child(odd){
        background: #c2e1d4;
    }
   
    table tr:nth-child(even){
        background: #cab2e2;
    }
</style>
'

$filePath = "C:\Test\Test.htm"

Get-Process | Select-Object Id,Name,CPU,Description -first 10 | ConvertTo-HTML -head $headStyle | Out-File $filePath

Invoke-Expression $filePath

  • First define a variable $headStyle with some CSS for our target HTML table.
  • $filePath is the file path where we will palce our HTML.
  • Then comes the key cmdlet. Get-Process will get current processes, then we include the pipeline with Select-Object cmdlet and only select our desired columns, i.e. Id, Name, CPU and Description.
  • -First 10 parameter will take top 10 rows, same like TOP keyword in SQL Server.
  • Again use pipeline to place the cmdlet for HTML conversion. i.e. ConvertTo-Html
    -head
    parameter contains the variable we defined so we could use our custom CSS.
  • Third pipeline added the Out-File cmdlet to save our HTML in file system.
  • Invoke-Expression will open the target HTML file in browser.

No comments:

Post a Comment