Your company's ad could live here and reach over 50,000 people a month!

Share This Post

PowerShell Function: Insert-TotalRow

When building reports with PowerShell I usually build a HTML page with a  StringBuilder and add multiple tables using the ConvertTo-HTML cmdlet. This function inserts a total row to output of ConvertTo-HTML cmdlet so I don’t have to handle it separately.

Function:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
function Insert-TotalRow {
    # Adds a total row to the output of the ConvertTo-HTML -fragment cmdlet
    $table = $input | %{$_}
    $table = [string]::Join("`n",$table)
    $cols = ([regex]::matches($table,"<col/>")).Count
    $total = ([regex]::matches($table,"<tr>")).Count  1
    if ($total -eq -1) {$total++}
    if ($cols -eq 0) {
        $table= $table.Insert($table.IndexOf("</table>"), "<tr><td colspan=`"$cols`" class=`"total`">Total: $total</td></tr>`n")
    }
    else {
        $table= $table.Insert($table.IndexOf("</colgroup>")+11, "`n<tr><td colspan=`"$cols`" class=`"total`">Total: $total</td></tr>`n")
    }
    $table
}

Example:

#Generic Example
$Systems | ConvertTo-Html -Fragment | Insert-TotalRow

#StringBuilder Example
[void]$html.Append(($Systems | ConvertTo-Html -Fragment | Insert-TotalRow))

 

Example Output:

Total: 5
Name Description OU LastLogonTimestamp
TURK Christopher Turk – Chief of Surgery Surgeons 3/5/2012 8:00:58 AM
DORIAN John Dorian (JD) – Co-Chief Resident Doctors 3/8/2012 4:42:29 AM
COX Perry Cox – Chief of Medicine Doctors 3/15/2012 9:54:47 AM
REID Elliot Reid (Blond Doctor) – Chief Resident Doctors 3/12/2012 11:23:19 AM
JANITOR Glenn Matthews (Janitor) – IT Administrator Admins 3/15/2012 9:54:57 AM

Share This Post

Leave a Reply