POWERSHELL基于ConvertTo-Htm指定单元格效果css风格html报表

                            基于ConvertTo-Htmcss风格和指定单元格效果html报表的生成

PowerShell本身具有一个简单但是很实用的命令 ConvertTo-Htm,可以把整个对象转换成HTML格式。事实上,作为基本的功能他已经可以实现一些漂亮的界面了。但是还是太基础了,不能满足大多数用户的需要。

一方面,Html风格能否为美轮美奂css。还有,如何指定具体某一个单元格的效果呢,让用户体验更好呢。比如说,希望把Item5列所为ERR内容的都标示红色。

网上有这类函数,但不巧的是要收费,不提供源代码在ConvertTo-Htm基础上,经过改造实现了上述设想。现提供源代码供大家参考。

POWERSHELL基于ConvertTo-Htm指定单元格效果css风格html报表

源代码如下:

Function Set-CellColor
{   <#
    .SYNOPSIS
        Function that allows you toset individual cell colors in an HTML table
    .DESCRIPTION
        To be used inconjunctionwith ConvertTo-HTML this simple function allows you
        to set particular colors forcells in an HTML table.  You provide thecriteria
        the script uses to make thedetermination if a cell should be a particular
        color (property -gt 5,property -like "*Apple*", etc).
       
        You can add the function toyour scripts, dot source it to load into your current
        PowerShell session or add itto your $Profile so it is always available.
       
        To dot source:
           ."./Set-CellColor.ps1"
           
    .PARAMETER Property
        Property, or column that youwill be keying on. 
    .PARAMETER Color
        Name or 6-digit hex value ofthe color you want the cell to be
    .PARAMETER InputObject
        HTML you want the script toprocess.  This can be entered directlyinto the
        parameter or piped to thefunction.
    .PARAMETER Filter
        Specifies a query todetermine if a cell should have its color changed.  $true
        results will make the colorchange while $false result will return nothing.
       
        Syntax
        <Property Name><Operator> <Value>
       
        <Property Name>::= thesame as $Property.  This must matchexactly
        <Operator>::="-eq" | "-le" | "-ge" | "-ne" |"-lt" | "-gt"| "-approx" | "-like" |"-notlike"
            <JoinOperator> ::="-and" | "-or"
            <NotOperator> ::="-not"
       
        The script first attempts to convert thecell to a number, and if it fails it will
        cast it as a string.  So 40 will be a number and you can use -lt,-gt, etc.  But 40%
        would be cast as a string soyou could only use -eq, -ne, -like, etc. 
    .PARAMETER Row
        Instructs the script tochange the entire row to the specified color instead of the individual cell.
    .INPUTS
        HTML with table
    .OUTPUTS
        HTML
    .EXAMPLE
        get-process | convertto-html| set-cellcolor -Propety cpu -Color red -Filter "cpu -gt 1000" |out-file c:/test/get-process.html
 
        Assuming Set-CellColor hasbeen dot sourced, run Get-Process and convert to HTML. 
        Then change the CPU cell tored only if the CPU field is greater than 1000.
       
    .EXAMPLE
        get-process | convertto-html| set-cellcolor cpu red -filter "cpu -gt 1000 -and cpu -lt 2000" |out-file c:/test/get-process.html
       
        Same as Example 1, but nowwe will only turn a cell red if CPU is greater than 100
        but less than 2000.
       
    .EXAMPLE
        $HTML = $Data | sort server| ConvertTo-html -head $header | Set-CellColor cookedvalue red -Filter"cookedvalue -gt 1"
        PS C:/> $HTML = $HTML |Set-CellColor Server green -Filter "server -eq 'dc2'"
        PS C:/> $HTML |Set-CellColor Path Yellow -Filter "Path -like""*memory*""" | Out-File c:/Test/colortest.html
       
        Takes a collection ofobjects in $Data, sorts on the property Server and converts to HTML.  From there
        we set the"CookedValue" property to red if it's greater then 1.  We then send the HTML through Set-CellColor
        again, this time setting theServer cell to green if it's "dc2". One more time through Set-CellColor
        turns the Path cell toYellow if it contains the word "memory" in it.
       
    .EXAMPLE
        $HTML = $Data | sort server| ConvertTo-html -head $header | Set-CellColor cookedvalue red -Filter"cookedvalue -gt 1" -Row
       
        Now, if the cookedvalueproperty is greater than 1 the function will highlight the entire row red.
       
    .NOTES
        Author:             Martin Pugh
        Twitter:            @thesurlyadm1n
        Spiceworks:         Martin9700
        Blog:               www.thesurlyadmin.com
         
        Changelog:
            1.5             Added ability to set row colorwith -Row switch instead of the individual cell
            1.03            Added error message in case the$Property field cannot be found in the table header
            1.02            Added some additional text tohelp.  Added some error trapping around$Filter
                           creation.
            1.01            Added verbose output
            1.0             Initial Release
    .LINK
       http://community.spiceworks.com/scripts/show/2450-change-cell-color-in-html-table-with-powershell-set-cellcolor
    #>
 
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory,Position=0)]
        [string]$Property,
       [Parameter(Mandatory,Position=1)]
        [string]$Color,
       [Parameter(Mandatory,ValueFromPipeline)]
        [Object[]]$InputObject,
        [Parameter(Mandatory)]
        [string]$Filter,
        [switch]$Row
    )
   
    Begin {
        Write-Verbose"$(Get-Date): Function Set-CellColor begins"
        If ($Filter)
        {   If($Filter.ToUpper().IndexOf($Property.ToUpper()) -ge 0)
            {   $Filter =$Filter.ToUpper().Replace($Property.ToUpper(),"`$Value")
                Try {
                   [scriptblock]$Filter = [scriptblock]::Create($Filter)
                }
                Catch {
                    Write-Warning"$(Get-Date): ""$Filter"" caused an error, stoppingscript!"
                    Write-Warning$Error[0]
                    Exit
                }
            }
            Else
            {   Write-Warning "Could not locate$Property in the Filter, which is required. Filter: $Filter"
                Exit
            }
        }
    }
   
    Process {
        ForEach ($Line in$InputObject)
        {   If($Line.IndexOf("<tr><th") -ge 0)
            {   Write-Verbose "$(Get-Date): Processingheaders..."
                $Search = $Line |Select-String -Pattern '<th ?[a-z/-:;"=]*>(.*?)<//th>'-AllMatches
                $Index = 0
                ForEach ($Match in$Search.Matches)
                {   If ($Match.Groups[1].Value -eq $Property)
                    {   Break
                    }
                    $Index ++
                }
                If ($Index -eq$Search.Matches.Count)
                {   Write-Warning "$(Get-Date): Unable tolocate property: $Property in table header"
                    Exit
                }
                Write-Verbose"$(Get-Date): $Property column found at index: $Index"
            }
            If ($Line -match"<tr(background-color:.+?"")?><td")
            {   $Search = $Line | Select-String -Pattern'<td ?[a-z/-:;"=]*>(.*?)<//td>' -AllMatches
                $Value =$Search.Matches[$Index].Groups[1].Value -as [double]
                If (-not $Value)
                {   $Value =$Search.Matches[$Index].Groups[1].Value
                }
                If (Invoke-Command$Filter)
                {   If ($Row)
                    {   Write-Verbose "$(Get-Date): Criteriamet!  Changing row to $Color..."
                        If ($Line-match "<trbackground-color:(.+?)"">")
                        {   $Line = $Line -replace "<trbackground-color:$($Matches[1])","<trbackground-color:$Color"
                        }
                        Else
                        {   $Line =$Line.Replace("<tr>","<tr background-color:$Color"">")
                        }
                    }
                    Else
                    {   Write-Verbose "$(Get-Date): Criteriamet!  Changing cell to $Color..."
                        $Line =$Line.Replace($Search.Matches[$Index].Value,"<tdbackground-color:$Color"">$Value</td>")
                    }
                }
            }
            Write-Output $Line
        }
    }
   
    End {
        Write-Verbose"$(Get-Date): Function Set-CellColor completed"
    }
}
 
 
 
 
function filestring-search($inputFile,$matchstring,$matchcount){
  $tmpcontent = Get-Content$inputFile
  for($i=0;$i -le$tmpcontent.length;i++)
  {
    if($tmpcontent[$i] -like'*Err*'){
    $matchcount++
    wite-host matchcount:$matchcount  -background red
    }
  }
  return
}
 
 
 
Function ConvertTo-AdvHTML
{   <#
    .SYNOPSIS
        Advanced replacement ofConvertTo-HTML cmdlet
    .DESCRIPTION
        This function allows forvastly greater control over cells and rows
        in a HTML table.  It takes ConvertTo-HTML to a whole newlevel!  You
        can now specify what color acell or row is (either dirctly or through
        the use of CSS).  You can add links, pictures and pictures ASlinks.
        You can also specify a cellto be a bar graph where you control the
        colors of the graph and textthat can be included in the graph.
       
        All color functions arethrough the use of imbedded text tags inside the
        properties of the object youpass to this function.  It is importantto note
        that this function does notdo any processing for you, you must make sure all
        control tags are alreadypresent in the object before passing it to the
        function.
       
        Here are the different tagsavailable:
       
        Syntax                          Comment
       ===================================================================================
       [cell:<color>]<optional text>   Designate the color of the cell.  Must be
                                       at the beginning of the string.
                                       Example:
                                           [cell:red]System Down
                                           
        [row:<color>]                   Designate the color of therow.  This control
                                       can be anywhere, in any property of the object.
                                       Example:
                                           [row:orchid]
                                           
       [cellclass:<class>]<optional text> 
                                       Designate the color, and other properties, of the
                                       cell based on a class in your CSS. You must
                                       have the class in your CSS (use the -CSS parameter).
                                       Must be at the beginning of the string.
                                       Example:
                                           [cellclass:highlight]10mb
                                           
       [rowclass:<class>]             Designate the color, and other properties, of the
                                       row based on a class in your CSS. You must
                                       have the class in your CSS (use the -CSS parameter).
                                       This control can be anywhere, in any property of the 
                                       object.
                                       Example:
                                           [rowclass:greyishbold]
                                           
       [p_w_picpath:<height;width;url>]<alternate text>
                                       Include an p_w_picpath in your cell. Put size of picture
                                       in pixels and url seperated by semi-colons.  Format
                                        must beheight;width;url.  You can also includeother
                                       text in the cell, but the [p_w_picpath] tag must be at the
                                       end of the tag (so the alternate text is last).
                                        Example:
                                           [p_w_picpath:100;200;http://www.sampleurl.com/samplep_w_picpath.jpg]Alt Text ForImage
                                           
        [link:<url>]<linktext>         Include a link in yourcell.  Other text is allowed in
                                       the string, but the [link] tag must be at the end of the
                                       string.
                                       Example:
                                           blah blah blah [link:www.thesurlyadmin.com]Cool PowerShell Link
                                           
       [linkpic:<height;width;url to pic>]<url for link>
                                       This tag uses a picture which you can click on and go to the
                                       specified link.  You must specifythe size of the picture and
                                       url where it is located, this information is seperated by semi-
                                       colons.  Other text is allowed inthe string, but the [link] tag
                                       must be at the end of the string.
                                       Example:
                                            [linkpic:100;200;http://www.sampleurl.com/samplep_w_picpath.jpg]www.thesurlyadmin.com
                                           
        [bar:<percent;barcolor;remainder color>]<optional text>
                                       Bar graph makes a simple colored bar graph within the cell.  The
                                       length of the bar is controlled using <percent>.  You can
                                       designate the color of the bar, and the color of the remainder
                                       section.  Due to the mysteries ofHTML, you must designate a
                                       width for the column with the [bar] tag using the HeadWidth parameter.
                                        
                                       So if you had a percentage of 95, say 95% used disk you
                                       would want to highlight the remainder for your report:
                                       Example:
                                            [bar:95;darkgreen;red]5% free
                                       
                                       What if you were at 30% of a sales goal with only 2 weeks left in
                                       the quarter, you would want to highlight that you have a problem.
                                       Example:
                                           [bar:30;darkred;red]30% of goal
    .PARAMETER InputObject
        The object you wantconverted to an HTML table
    .PARAMETER HeadWidth
        You can specify the width ofa cell.  Cell widths are in pixels
        and are passed to theparameter in array format.  Each element
        in the array corresponds tothe column in your table, any element
        that is set to 0 willdesignate the column with be dynamic.  Ifyou had
        four elements in yourInputObject and wanted to make the 4th a fixed
        width--this is required forusing the [bar] tag--of 600 pixels:
       
        -HeadWidth 0,0,0,600
    .PARAMETER CSS
        Designate custom CSS foryour HTML
    .PARAMETER Title
        Specifies a title for theHTML file, that is, the text that appears between the <TITLE> tags.
    .PARAMETER PreContent
        Specifies text to add beforethe opening <TABLE> tag. By default, there is no text in that position.
    .PARAMETER PostContent
        Specifies text to add afterthe closing </TABLE> tag. By default, there is no text in that position.
    .PARAMETER Body
        Specifies the text to addafter the opening <BODY> tag. By default, there is no text in thatposition.
    .PARAMETER Fragment
        Generates only an HTMLtable. The HTML, HEAD, TITLE, and BODY tags are omitted.
    .INPUTS
        System.Management.Automation.PSObject
        You can pipe any .NET objectto ConvertTo-AdvHtml.
    .OUTPUTS
        System.String
        ConvertTo-AdvHtml returnsseries of strings that comprise valid HTML.
    .EXAMPLE
        $Data = @"
Server,Description,Status,Disk
[row:orchid]Server1,Hello1,[cellclass:up]Up,"[bar:45;Purple;Orchid]55%Free"
Server2,Hello2,[cell:green]Up,"[bar:65;DarkGreen;Green]65% Used"
Server3,Goodbye3,[cell:red]Down,"[bar:95;DarkGreen;DarkRed]5%Free"
server4,This is quite a cooltest,[cell:green]Up,"[p_w_picpath:150;650;http://pughspace.files.wordpress.com/2014/01/test-connection.png]TestImages"
server5,SurlyAdmin,[cell:red]Down,"[link:http://thesurlyadmin.com]TheSurly Admin"
server6,MoreSurlyAdmin,[cell:purple]Updating,"[linkpic:150;650;http://pughspace.files.wordpress.com/2014/01/test-connection.png]http://thesurlyadmin.com"
"@
        $Data = $Data |ConvertFrom-Csv
        $HTML = $Data |ConvertTo-AdvHTML -HeadWidth 0,0,0,600 -PreContent"<p><h2>This might be the best reportEVER</h2></p><br>" -PostContent "<br>Done!$(Get-Date)" -Title "Cool Test!"
       
        This is some sample codewhere I try to put every possibile tag and use into a single set
        of data.  $Data is the PSObject 4 columns.  Default CSS is used, so the [cellclass:up]tag
        will not work but I left itthere so you can see how to use it.
    .NOTES
        Author:             Martin Pugh
        Twitter:            @thesurlyadm1n
        Spiceworks:         Martin9700
        Blog:               www.thesurlyadmin.com
         
        Changelog:
            1.0             Initial Release
    .LINK
       http://thesurlyadmin.com/convertto-advhtml-help/
    .LINK
       http://community.spiceworks.com/scripts/show/2448-create-advanced-html-tables-in-powershell-convertto-advhtml
    #>
    #requires -Version 2.0
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true,
           ValueFromPipeline=$true)]
        [Object[]]$InputObject,
        [string[]]$HeadWidth,
        [string]$CSS = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color:black;border-collapse: collapse;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color:black;background-color: #6495ED;font-size:120%;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color:black;}
</style>
"@,
        [string]$Title,
        [string]$PreContent,
        [string]$PostContent,
        [string]$Body,
        [switch]$Fragment
    )
   
    Begin {
        If ($Title)
        {  $CSS += "`n<title>$Title</title>`n"
        }
        $Params = @{
            Head = $CSS
        }
        If ($PreContent)
        {  $Params.Add("PreContent",$PreContent)
        }
        If ($PostContent)
        {  $Params.Add("PostContent",$PostContent)
        }
        If ($Body)
        {   $Params.Add("Body",$Body)
        }
        If ($Fragment)
        {   $Params.Add("Fragment",$true)
        }
        $Data = @()
    }
   
    Process {
        ForEach ($Line in $InputObject)
        {   $Data += $Line
        }
    }
   
    End {
        $Html = $Data |ConvertTo-Html @Params |Set-CellColor item5 red -Filter "item5 -eq'ERR'"
 
        $NewHTML = @()
        ForEach ($Line in $Html)
        {   If ($Line -like "*<th>*")
            {   If ($Headwidth)
                {   $Index = 0
                    $Reg = $Line |Select-String -AllMatches -Pattern "<th>(.*?)<//th>"
                    ForEach ($th in$Reg.Matches)
                    {   If ($Index -le ($HeadWidth.Count - 1))
                        {   If ($HeadWidth[$Index] -and$HeadWidth[$Index] -gt 0)
                            {   $Line = $Line.Replace($th.Value,"<thwidth:$($HeadWidth[$Index])px"">$($th.Groups[1])</th>")
                            }
                        }
                        $Index ++
                    }
                }
            }
       
            Do {
                Switch -regex($Line)
                {   "<td>/[cell:(.*?)/].*?<//td>"
                    {   $Line =$Line.Replace("<td>[cell:$($Matches[1])]","<tdbackground-color:$($Matches[1])"">")
                        Break
                    }
                   "/[cellclass:(.*?)/]"
                    {  $Line =$Line.Replace("<td>[cellclass:$($Matches[1])]","<tdclass=""$($Matches[1])"">")
                        Break
                    }
                   "/[row:(.*?)/]"
                    {   $Line =$Line.Replace("<tr>","<tr background-color:$($Matches[1])"">")
                        $Line =$Line.Replace("[row:$($Matches[1])]","")
                        Break
                    }
                   "/[rowclass:(.*?)/]"
                    {   $Line =$Line.Replace("<tr>","<trclass=""$($Matches[1])"">")
                        $Line =$Line.Replace("[rowclass:$($Matches[1])]","")
                        Break
                    }
                   "<td>/[bar:(.*?)/](.*?)<//td>"
                    {   $Bar = $Matches[1].Split(";")
                        $Width = 100- [int]$Bar[0]
                        If (-not$Matches[2])
                        {   $Text = "&nbsp;"
                        }
                        Else
                        {   $Text = $Matches[2]
                        }
                        $Line =$Line.Replace($Matches[0],"<td><divbackground-color:$($Bar[1]);float:left;width:$($Bar[0])%"">$Text</div><divbackground-color:$($Bar[2]);float:left;width:$width%"">&nbsp;</div></td>")
                        Break
                    }
                   "/[p_w_picpath:(.*?)/](.*?)<//td>"
                    {   $Image = $Matches[1].Split(";")
                        $Line =$Line.Replace($Matches[0],"<imgsrc=""$($Image[2])""alt=""$($Matches[2])""height=""$($Image[0])""width=""$($Image[1])""></td>")
                    }
                   "/[link:(.*?)/](.*?)<//td>"
                    {   $Line =$Line.Replace($Matches[0],"<a href=""$($Matches[1])"">$($Matches[2])</a></td>")
                    }
                   "/[linkpic:(.*?)/](.*?)<//td>"
                    {   $Images = $Matches[1].Split(";")
                        $Line =$Line.Replace($Matches[0],"<ahref=""$($Matches[2])""><imgsrc=""$($Image[2])""height=""$($Image[0])""width=""$($Image[1])""></a></td>")
                    }
                    Default
                    {   Break
                    }
                }
            } Until ($Line -notmatch"/[.*?/]")
            $NewHTML += $Line
        }
        Return $NewHTML
    }
}
 
 
 
$today = Get-Date -UFormat "%Y%m%d"
$LogFilePath = "C:/DayCheck/ftpLog_$today.txt"
 
 
 
 
$today = Get-Date -UFormat "%Y%m%d"
$TargetFileTxt= "C:/DayCheck/CheckResultALL.txt"
$TargetFileHtml= "C:/DayCheck/CheckResultALL.html"
 
if( Test-Path $TargetFileTxt ){
                       write-host  "$TargetFileTxt exist remove"
                       remove-item$TargetFileTxt -Force
}else {
                       write-host"create $TargetFileTxt "
                       New-Item -Path$TargetFileTxt -Type file  
}
 
 
 
remove-item C:/DayCheck/ResultOut.txt -Force
remove-item C:/DayCheck/CheckResult* -Force
 
New-Item -Path C:/DayCheck/*_result.txt  -Typefile
New-Item -Path C:/DayCheck/CheckResultSummaryALL.txt -Type file
New-Item -Path C:/DayCheck/ResultOut.txt  -Typefile
New-Item -Path C:/DayCheck/C:/DayCheck/CheckResultALL.txt  -Type file
 
$UserName = "daycheck"
$Password = "daycheck"
 
 
"item1,item2,item3,item4,item5,item6"|  Out-File -Encoding utf8  C:/DayCheck/CheckResultSummaryALL.csv
 
Import-Csv 'C:/DayCheck/MachineList.csv' |ForEach-Object{
          $OS = $_.OS
          $APP = $_.APP
          $IP = $_.IP
          $NAME = $_.NAME
         
          $RemoteFilename = "ftp://xx.xx.20.240/"+ $OS + "_"+ $NAME + "_all_"+ "20160722" +"07_" + "result.txt"
          $RemoteFilename     
          $filename = "C:/DayCheck/" + $OS +"_"+ $NAME + "_all_"+"20160722" + "07_"+ "result.txt"
 
 
          if ( Test-Path -Path $filename ) {
              write-host "search file $filenamebegining "
             
        $tmpcontent=Get-Content$filename | Where-Object { $_ -like '*Err*' }
       
        $matchcount=0
        foreach($element in$tmpcontent){
            $matchcount++
            #write-host"element $element "
           
        }
        write-host "search fileErr  : $matchcount " -background red
       
        if($matchcount -eq 1 )
        {
              "$APP,$NAME$IP,$OS,download,O K,$herffilename" | Out-File  -Encoding utf8  -Append C:/DayCheck/CheckResultSummaryALL.csv
        }else{
                               "$APP,$NAME$IP,$OS,download,ERR,$herffilename" | Out-File  -Encoding utf8  -Append C:/DayCheck/CheckResultSummaryALL.csv
        }
          }     else{
            
             "$APP,$NAME($IP),$OS,N/A,N/A,N/A"  |  Out-File -Encoding utf8 -Append C:/DayCheck/CheckResultSummaryALL.csv
          }
       
}
 
C:/DayCheck/*_result.txt>>C:/DayCheck/CheckResultTotalALL.txt
 
import-csv C:/DayCheck/CheckResultSummaryALL.csv |  ConvertTo-AdvHTML -HeadWidth 0,0,0,0,0,0-PreContent "<p><h2>This might be the best reportEVER</h2></p><br>" -PostContent "<br>Done!$(Get-Date)" -Title "Cool Test!" | Set-Content  "C:/DayCheck/CheckResultSummaryALL.html"
 
invoke-item C:/DayCheck/CheckResultSummaryALL.html

 

 

原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/186902.html

(0)
上一篇 2021年11月4日
下一篇 2021年11月4日

相关推荐

发表回复

登录后才能评论