PSWriteHTML.psm1
Function Get-Functions { PAram ( $pattern, $path = "$pwd\*", [switch]$Recurse = $false ) $parser = [System.Management.Automation.PSParser] Get-ChildItem (join-Path $path '\*') -Recurse:$Recurse -Include *.ps1, *.psm1 | ForEach { $content = [IO.File]::ReadAllText($_.FullName) $tokens = $parser::Tokenize($content, [ref] $null) $count = $tokens.Count $( for ($idx = 0; $idx -lt $count; $idx += 1) { if ($tokens[$idx].Content -eq 'function') { $targetToken = $tokens[$idx + 1] [PSCustomObject] @{ FileName = $_.FullName FunctionName = $targetToken.Content Line = $targetToken.StartLine } | Select FunctionName, FileName, Line } } ) #| Where {$_.FunctionName -match $pattern} } } Function Get-HTMLAnchor { <# .SYNOPSIS creates an Anchor .PARAMETER AnchorName The Actual Anchor #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [String] $AnchorName ) $Anchor = '<a name="' + $AnchorName + '"></a>' Write-Output $Anchor } Function Get-HTMLAnchorLink { <# .SYNOPSIS creates Hyperlink for an Anchor .PARAMETER AnchorName The Actual name of the Anchor (Hidden) .PARAMETER AnchorText The HyperLink text. Will default to $AnchorNname if not specified #> [CmdletBinding()] Param ( [Parameter(Mandatory = $false)] [String] $AnchorName, [Parameter(Mandatory = $true)] [String] $AnchorText ) if ($AnchorText -eq $null -or $AnchorText -eq '') {$AnchorText = $AnchorName} $report = '<a class="alink" href="#' + $AnchorName + '">' + $AnchorText + '</a>' Write-Output $report } Function Get-HTMLBarChart { <# .SYNOPSIS #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] $ChartObject, [Parameter(Mandatory = $true)] [Array] $DataSet, [Parameter(Mandatory = $false)] $Options ) $DataCount = $DataSet.Count Write-Verbose "Data Set counnt is $DataCount" if ($ChartObject.ChartStyle.ColorSchemeName -ne 'Random') { if ($Options -eq $null) { #Write-Verbose "Default Colour Schemes selected, selecting $($ChartObject.ChartStyle.ColorSchemeName)" #$ColorSchemes = Get-HTMLColorSchemes $ChartColorScheme = $GlobalColorSchemes.($ChartObject.ChartStyle.ColorSchemeName) | Select-Object -First $DataCount } else { Write-Verbose "Options Colour Schemes selected, selecting $($ChartObject.ChartStyle.ColorSchemeName)" $ChartColorScheme = $Options.ColorSchemes.($ChartObject.ChartStyle.ColorSchemeName) | Select-Object -First $DataCount } if ($ChartColorScheme.Count -lt $DataCount) { Write-Warning ("Colorscheme " + $ChartObject.ChartStyle.ColorSchemeName + " only has " + $ChartColorScheme.Count + " schemes, you have $DataCount Records. Generating one for you" ) $ChartColorScheme = Get-RandomColorScheme -numberofschemes $DataCount } } else { $ChartColorScheme = Get-RandomColorScheme -numberofschemes $DataCount } $ofs = ',' $CJSHeader = @() $CJSHeader += '<canvas id="' + $ChartObject.ObjectName + '" width="' + $ChartObject.Size.Width + '" height="' + $ChartObject.Size.Height + '"></canvas>' $CJSHeader += '<script>' $CJSHeader += 'var ctx = document.getElementById("' + $ChartObject.ObjectName + '");' $CJSHeader += 'var ' + $ChartObject.ObjectName + ' = new Chart(ctx, {' $CJSHeader += " type: '$($ChartObject.ChartStyle.ChartType)'," $CJSData = @() $CJSData = " data: {" + "`n" if ($ChartObject.ChartStyle.Showlabels) { $ofs = '","' $CJSData += ' labels: ["' + "$($DataSet.($ChartObject.DataDefinition.DataNameColumnName))" + '"],' + "`n" } $CJSData += " datasets: [{" + "`n" $CJSData += " label: '$($chartobject.DataDefinition.datasetname)'," + "`n" $ofs = "," $CJSData += " data: [" + "$($DataSet | % {$_.($ChartObject.DataDefinition.DataValueColumnName)})" + "]," + "`n" $ofs = "','" $CJSData += " backgroundColor: ['" + "$($ChartColorScheme.Background)" + "']," + "`n" $CJSData += " borderColor: ['" + "$($ChartColorScheme.border)" + "']," + "`n" $CJSData += " hoverBackgroundColor: ['" + "$($ChartColorScheme.border)" + "']," + "`n" $CJSData += " borderWidth: $($ChartObject.ChartStyle.borderWidth)" + "`n" $CJSData += " }]" + "`n" $CJSData += " }," $ofs = "" $CJSOptions = @() $cjsOptions += ' options: {' #responsive $cjsOptions += " responsive: $($ChartObject.ChartStyle.responsive)," #legend $cjsOptions += " legend: { position: '$($ChartObject.ChartStyle.legendposition)', }," #title if ($ChartObject.Title -ne '') { $cjsOptions += " title: { display: true, text: '$($ChartObject.Title)' }," } #scale & Labels $XAxisLabel = $ChartObject.DataDefinition.AxisXTitle if ([string]::IsNullOrEmpty($XAxisLabel)) { $displayXAxisLabel = 'false' } else { $displayXAxisLabel = 'true' } $YAxisLabel = $ChartObject.DataDefinition.AxisYTitle if ([string]::IsNullOrEmpty($YAxisLabel)) { $displayYAxisLabel = 'false' } else { $displayYAxisLabel = 'true' } $CJSOptions += "scales: { xAxes: [{ display: $displayXAxisLabel, scaleLabel: { display: $displayXAxisLabel, labelString: '$XAxisLabel' } }], yAxes: [{ display: $displayYAxisLabel, scaleLabel: { display: $displayYAxisLabel, labelString: '$YAxisLabel' }, ticks: { beginAtZero:true } }] }, " $cjsOptions += " }" + "`n" $CJSOptions += "}); " $CJSFooter = " </script>" $CJS = @() $CJS += $CJSHeader $CJS += $CJSData $CJS += $CJSOptions $CJS += $CJSFooter write-output $CJS } Function Get-HTMLBarChartObject { <# .SYNOPSIS create a Bar chart object for use with Get-HTMLBarChart #> [CmdletBinding()] param( [Parameter(Mandatory = $false)] $ColorScheme ) $ChartSize = [PSCustomObject] @{ Width = 500 Height = 400 } $DataDefinition = [PSCustomObject] @{ DataSetName = "Data" AxisXTitle = "" AxisYTitle = "" DataNameColumnName = "name" DataValueColumnName = "count" } if ($ColorScheme -eq "Generated") {$thisColorScheme = 'Generated' + [string](Get-Random -Minimum 1 -Maximum 8)} elseif ($ColorScheme -eq "Random") {$thisColorScheme = 'Random' } else {$thisColorScheme = 'ColorScheme1'} $ChartStyle = [PSCustomObject] @{ ChartType = "bar" ColorSchemeName = "$thisColorScheme" Showlabels = $true borderWidth = "1" responsive = 'false' legendPosition = 'bottom' } $ChartObject = [PSCustomObject] @{ ObjectName = -join ((65..90) + (97..122) | Get-Random -Count 12 | ForEach-Object {[char]$_}) Title = "" Size = $ChartSize DataDefinition = $DataDefinition ChartStyle = $ChartStyle } return $ChartObject } Function Get-HTMLCodeBlock { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [String] $Code, [Parameter(Mandatory = $false)] [String] $Style = 'PowerShell' ) $CodeBlock = @() switch ($Style) { 'PowerShell' { $CodeBlock += '<pre class="PowerShell">' } 'othercodestyleneedsACSSStyle' { $CodeBlock += '<pre class="PowerShell">' } default { $CodeBlock += '<pre>' } } $CodeBlock += $Code $CodeBlock += '</pre>' [string]$CodeBlock = $CodeBlock Write-Output $CodeBlock } Function Get-HTMLColorSchemes { [CmdletBinding()] param ( [Parameter(Mandatory = $false)][String]$SchemePath ) if ([String]::IsNullOrEmpty($SchemePath)) { $SchemePath = "$PSScriptRoot\Resources\ColorSchemas" } $Schemes = @{} Write-Verbose "Retrieving *.rcs from $SchemePath" $SchemeFiles = @(Get-ChildItem $SchemePath -Filter '*.rcs' -Recurse ) foreach ($SchemeFile in $SchemeFiles) { $SchemeContent = Import-Csv -Delimiter ';' -Path $SchemeFile.FullName $Schemes.Add($SchemeFile.BaseName, $SchemeContent) } $Schemes.add('Generated1', (Get-RandomColorScheme -NumberOfSchemes 80)) $Schemes.add('Generated2', (Get-RandomColorScheme -NumberOfSchemes 80)) $Schemes.add('Generated3', (Get-RandomColorScheme -NumberOfSchemes 80)) $Schemes.add('Generated4', (Get-RandomColorScheme -NumberOfSchemes 80)) $Schemes.add('Generated5', (Get-RandomColorScheme -NumberOfSchemes 80)) $Schemes.add('Generated6', (Get-RandomColorScheme -NumberOfSchemes 80)) $Schemes.add('Generated7', (Get-RandomColorScheme -NumberOfSchemes 80)) $Schemes.add('Generated8', (Get-RandomColorScheme -NumberOfSchemes 80)) Write-Output $Schemes } Function Get-HTMLColumn { [CmdletBinding()] param ( [Parameter(Mandatory = $false, ParameterSetName = 'open')] [int]$ColumnNumber = 1, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [int]$ColumnCount = 1, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [switch] $Open, [Parameter(Mandatory = $false, ParameterSetName = 'close')] [switch] $Close ) $HTML = New-GenericList -Type [string] if ($Open) { $ColumnItem = [string]$ColumnNumber + "of" + [string]$ColumnCount Write-Verbose $ColumnItem $ColumnItem = $ColumnItem.replace('1', 'one').replace('2', 'two').replace('3', 'three').replace('4', 'four').replace('5', 'five').replace('6', 'six') Write-Verbose $ColumnItem $HTML.Add('<div class="' + $ColumnItem + ' column">') } if ($Close) { $HTML.Add('</div>') } return $HTML } Function Get-HTMLContent { <# .SYNOPSIS Creates a section in HTML .PARAMETER HeaderText The heading for the section .PARAMETER IsHidden Switch parameter to define if the section can collapse .PARAMETER BackgroundShade An int for 1 to 6 that defines background shading #> [CmdletBinding()] Param ( [Parameter(Mandatory = $false)][string]$HeaderText, [Parameter(Mandatory = $false)][switch]$IsHidden, [Parameter(Mandatory = $false)][string]$Anchor, [Parameter(Mandatory = $false)][validateset(1, 2, 3, 4, 5, 6)][int]$BackgroundShade, [Parameter(Mandatory = $false)][switch] $CanCollapse, [switch] $Open, [switch] $Close ) $HTML = New-GenericList -Type [string] if ($Open) { switch ($BackgroundShade) { 1 { $bgColorCode = "#F8F8F8" } 2 { $bgColorCode = "#D0D0D0" } 3 { $bgColorCode = "#A8A8A8" } 4 { $bgColorCode = "#888888" } 5 { $bgColorCode = "#585858" } 6 { $bgColorCode = "#282828" } default { $bgColorCode = "#ffffff" } } if ([String]::IsNullOrEmpty($Anchor)) { $InsertAnchor = 'name="' + $Anchor + '"' } $RandomNumber = Get-Random if ($IsHidden) { $HTML.Add(@" <div class="section"> <div class="header"> <a name="$($HeaderText)">$($HeaderText)</a> (<a id="show_$RandomNumber" href="#" onclick="show('$RandomNumber');" style="color: #ffffff;">Show</a> <a id="hide_$RandomNumber" href="#" onclick="hide('$RandomNumber');" style="color: #ffffff; display:none;">Hide</a>) </div> <div class="content" id="$RandomNumber" style="display:none;background-color:$($bgColorCode);"> "@) } elseif ($CanCollapse) { $HTML.Add(@" <div class="section"> <div class="header"> <a name="$($HeaderText)">$($HeaderText)</a> (<a id="show_$RandomNumber" href="#" onclick="show('$RandomNumber');" style="color: #ffffff; display:none;">Show</a> <a id="hide_$RandomNumber" href="#" onclick="hide('$RandomNumber');" style="color: #ffffff; ">Hide</a>) </div> <div class="content" id="$RandomNumber" style="background-color:$($bgColorCode);"> "@) } else { $HTML.Add(@" <div class="section"> <div class="header"> <a name="$($HeaderText)">$($HeaderText)</a> </div> <div class="content" style="background-color:$($bgColorCode);"> "@) } } if ($Close) { $HTML.Add('</div></div>') } Return $HTML } Function Get-HTMLContentDataTable { <# .SYNOPSIS Creates an HTML 5 Data table from an array of objects .PARAMETER ArrayOfObjects An array of objects .PARAMETER Paging .PARAMETER PagingOptions .PARAMETER Ordering .PARAMETER Info .PARAMETER HideFooter #> param ( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [alias('ArrayOfObjects', 'DataTable', 'Table')][Array]$Object, [Parameter(Mandatory = $false, ValueFromPipeline = $false)] [switch]$DisablePaging, [Parameter(Mandatory = $false, ValueFromPipeline = $false)] [string]$PagingOptions = '15,25, 50, 100,', [Parameter(Mandatory = $false, ValueFromPipeline = $false)] [switch]$DisableOrdering, [Parameter(Mandatory = $false, ValueFromPipeline = $false)] [switch]$DisableInfo, [Parameter(Mandatory = $false, ValueFromPipeline = $false)] [switch]$HideFooter, [switch]$DisableColumnReorder, [switch]$DisableResponsiveTable, [switch]$DisableSelect ) if ($DisablePaging) {$Paging = 'false'} else {$Paging = 'true'} if ($DisableOrdering) {$Ordering = 'false'} else {$Ordering = 'true'} if ($DisableInfo) {$Info = 'false'} else {$Info = 'true'} if ($DisableColumnReorder) { $ColumnReorder = 'false' } else { $ColumnReorder = 'true' } if ($DisableResponsiveTable) { $ResponsiveTable = 'false' } else { $ResponsiveTable = 'true' } if ($DisableSelect) { $Select = 'false' } else { $Select = 'true' } [string] $DTInstance = Get-RandomStringName -Size 8 $TableHeader = @' <script> $(document).ready(function() { $('# '@ $TableHeader += $DTInstance $TableHeader += @" ').DataTable({ dom: 'Bfrtip', buttons: [ 'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ], "paging": $($Paging), "pagingType": "full_numbers", "lengthMenu": [[$PagingOptions -1], [$PagingOptions "All"]], "ordering": $($Ordering), "info": $($Info), "colReorder": $($ColumnReorder), "responsive": { details: $($ResponsiveTable) }, "select": $($Select), "columns": [ "@ $ArraryHeader = $Object | ConvertTo-Html -Fragment $HeadersText = ($ArraryHeader[2] -replace '<tr>', '' -replace '<th>', '' -replace '</tr>', '') $ColumnHeaders = ($HeadersText.substring(0, $HeadersText.Length - 5)) -split '</th>' foreach ($ColumnHeader in $ColumnHeaders ) { $TableHeader += '{ "data": "' + $ColumnHeader + '" },' } $TableHeader += @' ] }); } ); </script> '@ $TableHeader = $TableHeader.Replace(',]', ']') $NumberOfColumns = ($Object | Get-Member -MemberType NoteProperty | Select-Object Name).Count $Report = $Object | ConvertTo-Html -Fragment <# Sample view of output <table> <colgroup><col/><col/><col/><col/></colgroup> <tr><th>ForestMode</th><th>Name</th><th>RootDomain</th><th>SchemaMaster</th></tr> <tr><td>Windows2012R2Forest</td><td>ad.evotec.xyz</td><td>ad.evotec.xyz</td><td>AD1.ad.evotec.xyz</td></tr> </table> When formatted: <table> <colgroup> <col /> <col /> <col /> <col /> </colgroup> <tr> <th>ForestMode</th> <th>Name</th> <th>RootDomain</th> <th>SchemaMaster</th> </tr> <tr> <td>Windows2012R2Forest</td> <td>ad.evotec.xyz</td> <td>ad.evotec.xyz</td> <td>AD1.ad.evotec.xyz</td> </tr> </table> #> # Removes colgroup and col that is empty $Report = $Report -replace '<col/>', "" -replace '<colgroup>', "" -replace '</colgroup>', "" # Connects Table Header with Table by replacing Table Tag with new tag and thead $Report = $Report -replace '<table>', ('<table id="' + $DTInstance + '" class="display compact"><thead>') # This splits 1st row from the rest of the table making it table header, closes theader and opens up tbody $Report = $Report -replace '</th></tr>', '</th></tr></thead><tbody>' # This closes body instead of table $Report = $Report -replace "</table>", "</tbody>" if (-not $HideFooter) { # this fixes footer (column names at the bottom of table) $Footer = '<tfoot><tr>' foreach ($Header in $ColumnHeaders) { $Footer += '<th>' + $Header + '</th>' } $Footer += '</tr></tfoot>' $Report += $Footer # $Report = $Report -replace "LoadFooterHere", $Footer } #$Report = $Report -replace 'URL01NEW', '<a target="_blank" href="' #$Report = $Report -replace 'URL01', '<a href="' #$Report = $Report -replace 'URL02', '">' #$Report = $Report -replace 'URL03', '</a>' $Report += "</table>" return ($TableHeader + $Report) } Function Get-HTMLContentTable { <# .SYNOPSIS Creates an HTML table from an array of objects .PARAMETER ArrayOfObjects An array of objects .PARAMETER Fixed fixes the html column width by the number of columns .PARAMETER GroupBy The column to group the data. make sure this is first in the array .PARAMETER Column Totals an Array of headers from that exist in the array of objects to be summed up #> [CmdletBinding()] param( [Array]$ArrayOfObjects, [String]$GroupBy, [Array]$ColumnCounts, [Switch]$Fixed, [Array]$ColumnAverages, [Switch]$NoSortableHeader, [Array]$ColumnTotals ) if ($GroupBy -eq '') { Write-Verbose "Get-HTMLContentTable - Running this option 1" $Report = $ArrayOfObjects | ConvertTo-Html -Fragment $Report = $Report -replace '<col/>', "" -replace '<colgroup>', "" -replace '</colgroup>', "" $Report = $Report -replace "<tr>(.*)<td>Green</td></tr>", "<tr class=`"green`">`$+</tr>" $Report = $Report -replace "<tr>(.*)<td>Yellow</td></tr>", "<tr class=`"yellow`">`$+</tr>" $Report = $Report -replace "<tr>(.*)<td>Red</td></tr>", "<tr class=`"red`">`$+</tr>" $Report = $Report -replace "<tr>(.*)<td>Odd</td></tr>", "<tr class=`"odd`">`$+</tr>" $Report = $Report -replace "<tr>(.*)<td>Even</td></tr>", "<tr class=`"even`">`$+</tr>" $Report = $Report -replace "<tr>(.*)<td>None</td></tr>", "<tr>`$+</tr>" $Report = $Report -replace '<th>RowColor</th>', '' if ($Fixed) { $Report = $Report -replace '<table>', '<table class="fixed">' } else { if (!($NoSortableHeader)) { $Report = $Report -replace '<table>', '<table class="sortable">' } } } else { Write-Verbose "Get-HTMLContentTable - Running this option 2" $NumberOfColumns = ($ArrayOfObjects | Get-Member -MemberType NoteProperty | Select-Object Name).Count $Groupings = @() $ArrayOfObjects | Select-Object $GroupBy -Unique | Sort-Object $GroupBy | ForEach-Object { $Groupings += [String]$_.$GroupBy} if ($Fixed) { $Report = '<table class="fixed">' } else { $Report = '<table>' } $GroupHeader = $ArrayOfObjects | ConvertTo-Html -Fragment $GroupHeader = $GroupHeader -replace '<col/>', "" -replace '<colgroup>', "" -replace '</colgroup>', "" -replace '<table>', "" -replace '</table>', "" -replace "<td>.+?</td>" -replace "<tr></tr>", "" $GroupHeader = $GroupHeader -replace '<th>RowColor</th>', '' $Report += $GroupHeader foreach ($Group in $Groupings) { $Report += "<tr><td colspan=`"$NumberOfColumns`" class=`"groupby`">$Group</td></tr>" $GroupBody = $ArrayOfObjects | Where-Object { [String]$($_.$GroupBy) -eq $Group } | Select-Object * -ExcludeProperty $GroupBy | ConvertTo-Html -Fragment $GroupBody = $GroupBody -replace '<col/>', "" -replace '<colgroup>', "" -replace '</colgroup>', "" -replace '<table>', "" -replace '</table>', "" -replace "<th>.+?</th>" -replace "<tr></tr>", "" -replace '<tr><td>', "<tr><td></td><td>" $GroupBody = $GroupBody -replace "<tr>(.*)<td>Green</td></tr>", "<tr class=`"green`">`$+</tr>" $GroupBody = $GroupBody -replace "<tr>(.*)<td>Yellow</td></tr>", "<tr class=`"yellow`">`$+</tr>" $GroupBody = $GroupBody -replace "<tr>(.*)<td>Red</td></tr>", "<tr class=`"red`">`$+</tr>" $GroupBody = $GroupBody -replace "<tr>(.*)<td>Odd</td></tr>", "<tr class=`"odd`">`$+</tr>" $GroupBody = $GroupBody -replace "<tr>(.*)<td>Even</td></tr>", "<tr class=`"even`">`$+</tr>" $GroupBody = $GroupBody -replace "<tr>(.*)<td>None</td></tr>", "<tr>`$+</tr>" $Report += $GroupBody } } # Not sure what that is for, must be something that ReportHTML guy was using - will be removed $Report = $Report -replace 'URL01NEW', '<a target="_blank" href="' $Report = $Report -replace 'URL01', '<a href="' $Report = $Report -replace 'URL02', '">' $Report = $Report -replace 'URL03', '</a>' if ($Report -like "*<tr>*" -and $report -like "*odd*" -and $report -like "*even*") { $Report = $Report -replace "<tr>", '<tr class="header">' } if ($ColumnTotals.count -gt 0 -or $ColumnAverages.count -gt 0 -or $ColumnCounts.count -gt 0 ) { Write-Verbose "Get-HTMLContentTable - Running this option 3" $TableFooter = $ArrayOfObjects | ConvertTo-Html -Fragment $TableFooter = $TableFooter -replace '<col/>', "" -replace '<colgroup>', "" -replace '</colgroup>', "" -replace '<table>', "" -replace '</table>', "" -replace "<td>.+?</td>" -replace "<tr></tr>", "" $TableFooter = $TableFooter -replace '<th>RowColor</th>', '' #$ColumnTotal foreach ($ColumnTotal in $ColumnTotals) { $TableFooter = $TableFooter -replace $ColumnTotal, ("sum:" + ($arrayofobjects | measure $ColumnTotal -Sum ).sum) } #ColumnAverage foreach ($ColumnAverage in $ColumnAverages) { $TableFooter = $TableFooter -replace $ColumnAverage, ("avg:" + ($arrayofobjects | measure $ColumnAverage -Average ).average) } #ColumnCount foreach ($ColumnCount in $ColumnCounts) { $TableFooter = $TableFooter -replace $ColumnCount, ("count:" + ($arrayofobjects | measure $ColumnCount).count) } #Cleanup foreach ($Column in ($ArrayOfObjects | Get-Member )) { $TableFooter = $TableFooter -replace ("<th>" + $Column.Name + "</th>"), '<td></td>' } $TableFooter = $TableFooter -replace '<th>', '<td class="totalrow">' -replace "</th>", '</td>' $TableFooter = $TableFooter -replace '<tr>', '<tr class="totalrow">' $Report = $Report -replace "</table>", "" $Report += "<tfoot>" $Report += $TableFooter $Report += "</tfoot>" # We need to close the table because we removed closing to add TableFooters. $Report += "</table>" } return $Report } Function Get-HTMLContentTableAdvanced { <# .SYNOPSIS Code borrowed from https://www.powershellgallery.com/packages/EnhancedHTML2 #> [CmdletBinding()] param( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [Array]$ArrayOfObjects ) $out = '' $out += "<table>" foreach ($object in $ArrayOfObjects) { $datarow = '' $headerrow = '' $properties = $object | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name foreach ($prop in $properties) { #$prop = $properties[0] $name = $null $value = $null if ($prop -is [string]) { $name = $Prop $value = $object.($prop) } else { Write-Warning "Unhandled property $prop" } $headerrow += "<th>$name</th>" $datarow += "<td>$value</td>" } if (-not $wrote_first_line ) { $out += "<tr>$headerrow</tr><tbody>" $wrote_first_line = $true } $out += "<tr>$datarow</tr>" } $out += "</table>" return $out } Function Get-HTMLContentText { <# .SYNOPSIS Creates an HTML entry with heading and detail .PARAMETER Heading The type of logo .PARAMETER Detail Some additional pish #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [String] $Heading, [Parameter(Mandatory = $false)] [String] $Detail ) $Report = @" <table><tbody> <tr> <th class="content">$Heading</th> <td class="content">$($Detail)</td> </tr> </tbody></table> "@ $Report = $Report -replace 'URL01NEW', '<a target="_blank" href="' $Report = $Report -replace 'URL01', '<a href="' $Report = $Report -replace 'URL02', '">' $Report = $Report -replace 'URL03', '</a>' Return $Report } Function Get-HTMLCSS { <# .SYNOPSIS Get's HTML Cascading Style Sheet .PARAMETER CSSName Name of the CSS #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)][String] $CSSPath, [Parameter(Mandatory = $false)][String] $CSSName, [switch] $Builtin, [switch] $UseLinks ) $CSSHeaders = New-GenericList -Type [string] if ($Builtin) { if ($UseLinks) { $Links = @( "https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/af-2.3.2/b-1.5.4/b-colvis-1.5.4/b-html5-1.5.4/b-print-1.5.4/cr-1.5.0/fc-3.2.5/fh-3.1.4/kt-2.5.0/r-2.2.2/rg-1.1.0/rr-1.2.4/sc-1.5.0/sl-1.2.6/datatables.min.css" ) foreach ($Link in $Links) { [string] $HTMLLink = '<link rel="stylesheet" type="text/css" href="**Link**"/>'.Replace('**Link**', $Link) $CSSHeaders.Add($HTMLLink) $CSSHeaders.Add("`r`n") } return $CSSHeaders } else { $CSSPath = "$PSScriptRoot\Resources\CSS\StylesAlways" } } else { if ([String]::IsNullOrEmpty($CSSPath)) { $CSSPath = "$PSScriptRoot\Resources\CSS\Styles" } } Write-Verbose "Retrieving *.css from $CSSPath" $CSSFiles = @((get-childitem $CSSPath -Filter '*.css' -Recurse)) if (-not $Builtin) { # By builtin we mean CSS that is part of JS Packages. This is limiting choice to single CSS to make sure reports look properly $CSSFiles = $CSSFiles | Where-Object { $_.BaseName -eq $CSSName } } foreach ($CssFile in $CSSFiles) { $CSSHeaders.Add('<style type="text/css">') $CSSHeaders.Add("`r`n") if ($CssFile -like '*.min.*') { Write-Verbose "Generating Style Header from - $($CssFile.FullName) (minified file)" $CSSHeaders.Add((Get-Content -Path $CssFile.FullName)) } else { Write-Verbose "Generating Style Header from - $($CssFile.FullName) (from non-minified file (adding delimiter))" $CSSHeaders.Add((Get-Content -Path $CssFile.FullName -Delimiter "`r`n")) } $CSSHeaders.Add("</style>") $CSSHeaders.Add("`r`n") } Write-Output $CSSHeaders } Function Get-HTMLHeading { Param ( [string]$headingText, [int]$headerSize ) $headerString = "<h$headerSize>$headingText</h$headerSize>" return $headerString } Function Get-HTMLJavaScripts { <# .SYNOPSIS Get's Script File from module directory #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)][String]$ScriptPath, [switch] $UseLinks ) $ScriptHeaders = New-GenericList -Type [string] if ($UseLinks) { $Links = @( "https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/af-2.3.2/b-1.5.4/b-colvis-1.5.4/b-html5-1.5.4/b-print-1.5.4/cr-1.5.0/fc-3.2.5/fh-3.1.4/kt-2.5.0/r-2.2.2/rg-1.1.0/rr-1.2.4/sc-1.5.0/sl-1.2.6/datatables.min.js" "https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js" "https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js" "https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js" "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js" ) foreach ($Link in $Links) { [string] $HTMLLink = '<script type="text/javascript" src="**Link**"></script>'.Replace('**Link**', $Link) $ScriptHeaders.Add($HTMLLink) $ScriptHeaders.Add("`r`n") } # Only some links are available online, so some static resources need to be put in. Maybe there is a way to put on CDN. # For now we need to reload this function again. $ScriptHeaders.Add((Get-HTMLJavaScripts -ScriptPath "$PSScriptRoot\Resources\JS\Static")) } else { if ([String]::IsNullOrEmpty($ScriptPath)) { $ScriptPath = "$PSScriptRoot\Resources\JS" } Write-Verbose "Retrieving *.js from $ScriptPath" $ScriptFiles = @((get-childitem $ScriptPath -Filter '*.js' -Recurse)) foreach ($ScriptFile in $ScriptFiles) { $ScriptHeaders.Add("`r`n") $ScriptHeaders.Add('<script type="text/javascript">') $ScriptHeaders.Add("`r`n") if ($ScriptFile -like '*.min.*') { Write-Verbose "Generating Script Header from minified file - $($ScriptFile.Fullname)" $ScriptHeaders.Add((Get-Content -Path $ScriptFile.Fullname)) } else { Write-Verbose "Generating Script Header from non-minified file (adding delimiter) $($ScriptFile.Fullname)" $ScriptHeaders.Add((Get-Content -Path $ScriptFile.Fullname -Delimiter "`r`n")) } $ScriptHeaders.Add('</script>') $ScriptHeaders.Add("`r`n") } } Write-Output $ScriptHeaders } Function Get-HTMLLogos { <# .SYNOPSIS Get Base64 HTML #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [String] $LogoPath, [switch] $Builtin ) if ($Builtin) { $LogoPath = "$PSScriptRoot\Resources\Images" } else { if ([String]::IsNullOrEmpty($LogoPath)) { return @{} } } $LogoSources = @{} $ImageFiles = Get-ChildItem -Path (join-path $LogoPath '\*') -Include *.jpg, *.png, *.bmp -Recurse foreach ($ImageFile in $ImageFiles) { if ($ImageFile.Extension -eq '.jpg') { $FileType = 'jpeg' } else { $FileType = $ImageFile.Extension.Replace('.', '') } Write-Verbose "Converting $($ImageFile.FullName) to base64 ($FileType)" $LogoSources.Add($ImageFile.BaseName, "data:image/$FileType;base64," + [Convert]::ToBase64String((Get-Content $ImageFile.FullName -Encoding Byte))) } Write-Output $LogoSources } Function Get-HTMLPage { [CmdletBinding(DefaultParameterSetName = 'options')] param ( [Parameter(Mandatory = $false, ParameterSetName = 'options')] [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][String]$TitleText, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][String]$CSSPath, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][String]$CSSName = "default", [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][String]$ScriptPath, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][String]$ColorSchemePath, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][String]$LogoPath, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][string]$LeftLogoName = "Sample", [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][string]$RightLogoName = "Alternate", [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][string]$LeftLogoString, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][string]$RightLogoString, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'options')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][switch]$HideLogos, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'options')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][switch]$HideTitle, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'options')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][switch]$NoScript, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'options')][PSobject]$Options, [Parameter(Mandatory = $false, ParameterSetName = 'explicit')][string]$PrimaryColorHex, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [switch] $AddAuthor, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [string] $Author, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [switch] $HideDate, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [string] $DateFormat = 'yyyy-MM-dd HH:mm:ss', [Parameter(Mandatory = $false, ParameterSetName = 'open')] [switch] $UseCssLinks, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [switch] $UseStyleLinks, [Parameter(Mandatory = $false, ParameterSetName = 'open')] [Parameter(Mandatory = $false, ParameterSetName = 'options')] [Parameter(Mandatory = $false, ParameterSetName = 'explicit')] [switch] $Open, [Parameter(Mandatory = $false, ParameterSetName = 'close')] [switch] $Close, [Parameter(Mandatory = $false, ParameterSetName = 'close')] [String]$FooterText # For closing param ) if ($Open) { [string] $CurrentDate = (Get-Date).ToString($DateFormat) #Get-Date #-format "MMM d, yyyy hh:mm tt" if ($PSCmdlet.ParameterSetName -eq 'options') { if ($Options -eq $null) { $Options = New-HTMLReportOptions -UseCssLinks:$UseCssLinks -UseStyleLinks:$UseStyleLinks } } else { if ([String]::IsNullOrEmpty($RightLogoString) -eq $false -or [String]::IsNullOrEmpty($LeftLogoString) -eq $false) { $LogoSources = @{} if ([String]::IsNullOrEmpty($RightLogoString) -eq $false) { $LogoSources.Add($RightLogoName, $RightLogoString) } if ([String]::IsNullOrEmpty($LeftLogoString) -eq $false) { $LogoSources.Add($LeftLogoName, $LeftLogoString) } } if (!([String]::IsNullOrEmpty($LogoPath))) { $LogoSources = Get-HTMLLogos -logopath $LogoPath } $Options = New-HTMLReportOptions -LogoSources $LogoSources -CSSName $CSSName -CSSPath $CSSPath -ScriptPath $ScriptPath -ColorSchemePath $ColorSchemePath -UseCssLinks:$UseCssLinks -UseStyleLinks:$UseStyleLinks } if ($HideLogos -eq $false) { $Leftlogo = $Options.Logos[$LeftLogoName] $Rightlogo = $Options.Logos[$RightLogoName] $LogoContent = @" <table><tbody> <tr> <td class="clientlogo"><img src="$Leftlogo" /></td> <td class="MainLogo"><img src="$Rightlogo" /></td> </tr> </tbody></table> "@ } # Replace PNG / JPG files in Styles if ($null -ne $Options.StyleContent) { Write-Verbose "Logos: $($Options.Logos.Keys -join ',')" foreach ($Logo in $Options.Logos.Keys) { $Search = "../images/$Logo.png", "DataTables-1.10.18/images/$Logo.png" $Replace = $Options.Logos[$Logo] foreach ($S in $Search) { $Options.StyleContent = ($Options.StyleContent).Replace($S, $Replace) } } } $HTML = New-GenericList -Type [string] $HTML.Add("<!DOCTYPE HTML>") if ($AddAuthor) { if ([String]::IsNullOrWhiteSpace($Author)) { $Author = $env:USERNAME } $HTML.Add("<!--- This page was autogenerated $CurrentDate By $Author -->") } $HTML.Add("<html>") $HTML.Add('<!-- Header -->') $HTML.Add('<head>') if ($HideTitle -eq $false) { $HTML.Add("<Title>$TitleText</Title>") } $HTML.Add("<!-- Styles -->") $HTML.Add("$($Options.StyleContent)") $HTML.Add('<!-- Scripts -->') $HTML.Add("$($Options.ScriptContent)") $HTML.Add('</head>') $HTML.Add('') $HTML.Add('<!-- Body -->') #$HTML.Add('<body onload="hide();">') $HTML.Add('<body>') if (-not $HideTitle) { $HTML.Add("<!-- Report Header -->") $HTML.Add($LogoContent) $HTML.Add("<div class=`"pageTitle`">$TitleText</div>") $HTML.Add("<hr />") } if (-not $HideDate) { $HTML.Add("<div class=`"ReportCreated`">Report created on $($CurrentDate)</div>") } if (!([string]::IsNullOrEmpty($PrimaryColorHex))) { if ($PrimaryColorHex.Length -eq 7) { $HTML = $HTML -replace '#337E94', $PrimaryColorHex } else { Write-Warning '$PrimaryColorHex must be 7 characters with hash eg "#337E94"' } } Write-Output $HTML } if ($Close) { if ($null -ne $FooterText) { $FooterText = "Copyright © $([DateTime]::Now.Year). All Rights Reserved." } $HTML = @" <hr /> <!-- FOOTER --> <div class="footer">$FooterText</div> <!-- END BODY --> </body> </html> "@ Write-Output $HTML } } Function Get-HTMLPieChart { <# .SYNOPSIS #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] $ChartObject, [Parameter(Mandatory = $true)] [Array] $DataSet, [Parameter(Mandatory = $false)] $Options ) $DataCount = $DataSet.Count Write-Verbose "Data Set counnt is $DataCount" if ($ChartObject.ChartStyle.ColorSchemeName -ne 'Random') { if ($Options -eq $null) { #Write-Verbose "Default Colour Schemes selected, selecting $($ChartObject.ChartStyle.ColorSchemeName)" #$ColorSchemes = Get-HTMLColorSchemes $ChartColorScheme = $GlobalColorSchemes.($ChartObject.ChartStyle.ColorSchemeName) | select -First $DataCount } else { Write-Verbose "Options Colour Schemes selected, selecting $($ChartObject.ChartStyle.ColorSchemeName)" $ChartColorScheme = $Options.ColorSchemes.($ChartObject.ChartStyle.ColorSchemeName) | select -First $DataCount } if ($ChartColorScheme.Count -lt $DataCount) { Write-Warning ("Colorscheme " + $ChartObject.ChartStyle.ColorSchemeName + " only has " + $ChartColorScheme.Count + " schemes, you have $DataCount Records. Generating one for you" ) $ChartColorScheme = Get-RandomColorScheme -numberofschemes $DataCount } } else { $ChartColorScheme = Get-RandomColorScheme -numberofschemes $DataCount } $ofs = ',' $CJSHeader = @() $CJSHeader += '<canvas id="' + $ChartObject.ObjectName + '" width="' + $ChartObject.Size.Width + '" height="' + $ChartObject.Size.Height + '"></canvas>' $CJSHeader += '<script>' $CJSHeader += 'var ctx = document.getElementById("' + $ChartObject.ObjectName + '");' $CJSHeader += 'var ' + $ChartObject.ObjectName + ' = new Chart(ctx, {' $CJSHeader += " type: '$($ChartObject.ChartStyle.ChartType)'," $CJSData = @() $CJSData = " data: {" + "`n" if ($ChartObject.ChartStyle.Showlabels) { $ofs = '","' $CJSData += ' labels: ["' + "$($DataSet.($ChartObject.DataDefinition.DataNameColumnName))" + '"],' + "`n" } $CJSData += " datasets: [{" + "`n" $CJSData += " label: '$($chartobject.DataDefinition.datasetname)'," + "`n" $ofs = "," $CJSData += " data: [" + "$($DataSet | Foreach-Object {$_.($ChartObject.DataDefinition.DataValueColumnName)})" + "]," + "`n" $ofs = "','" $CJSData += " backgroundColor: ['" + "$($ChartColorScheme.Background)" + "']," + "`n" $CJSData += " hoverBackgroundColor: ['" + "$($ChartColorScheme.border)" + "']," + "`n" $CJSData += " borderWidth: $($ChartObject.ChartStyle.borderWidth)" + "`n" $CJSData += " }]" + "`n" $CJSData += " }," $ofs = "" $CJSOptions = @() $cjsOptions += ' options: {' #responsive $cjsOptions += " responsive: $($ChartObject.ChartStyle.responsive)," #legend $cjsOptions += " legend: { position: '$($ChartObject.ChartStyle.legendposition)', }," #Title if ($ChartObject.Title -ne '') { $cjsOptions += " title: { display: true, text: '$($ChartObject.Title)' }," } $cjsOptions += " }," #animation $cjsOptions += " animation: { animateScale: $($ChartObject.ChartStyle.animateScale), animateRotate: $($ChartObject.ChartStyle.animateRotate) }" $CJSOptions += "}); " $CJSFooter = " </script>" $CJS = @() $CJS += $CJSHeader $CJS += $CJSData $CJS += $CJSOptions $CJS += $CJSFooter write-output $CJS } Function Get-HTMLPieChartObject { <# .SYNOPSIS create a Bar chart object for use with Get-HTMLBarChart #> [CmdletBinding()] param( [ValidateSet("pie", "doughnut")] [String] $ChartType = 'pie', [Parameter(Mandatory = $false)] $ColorScheme ) $ChartSize = [PSCustomObject] @{ Width = 500 Height = 400 } $DataDefinition = [PSCustomObject] @{ DataSetName = "Data" DataNameColumnName = "name" DataValueColumnName = "count" } if ($ColorScheme -eq "Generated") { $thisColorScheme = 'Generated' + [string](Get-Random -Minimum 1 -Maximum 8) } elseif ( $ColorScheme -eq "Random") { $thisColorScheme = 'Random' } else { $thisColorScheme = 'ColorScheme2' } $ChartStyle = [PSCustomObject] @{ ChartType = $ChartType ColorSchemeName = "$thisColorScheme" Showlabels = $true borderWidth = "1" responsive = 'false' animateScale = 'true' animateRotate = 'true' legendPosition = 'bottom' } $ChartObject = [PSCustomObject] @{ ObjectName = -join ((65..90) + (97..122) | Get-Random -Count 12 | ForEach-Object {[char]$_}) Title = "" Size = $ChartSize DataDefinition = $DataDefinition ChartStyle = $ChartStyle } return $ChartObject } Function Get-HTMLPowerShellSyntax { [CmdletBinding()] Param ( $PowerShellFilePath ) # # Original Author: Lee Holmes, http://www.leeholmes.com/blog/MorePowerShellSyntaxHighlighting.aspx # # Modified by: Helge Klein, http://blogs.sepago.de/helge/ # # # Syntax highlights a PowerShell script. # # Usage: Supply the script to syntax hightligh as first and only parameter # # Output: Copy of original script with extension ".html" # # Example: .\Highlight-Syntax.ps1 .\Get-AppVPackageDependencies.ps1 # # Version history: # # 1.1: # # - Loading the required assembly System.Web now. This was missing earlier. # # 1.0: Initial version # $path = $PowerShellFilePath # Load required assemblies [void] [System.Reflection.Assembly]::Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") $tokenColours = @{ 'Attribute' = '#FFADD8E6' 'Command' = '#FF0000FF' 'CommandArgument' = '#FF8A2BE2' 'CommandParameter' = '#FF000080' 'Comment' = '#FF006400' 'GroupEnd' = '#FF000000' 'GroupStart' = '#FF000000' 'Keyword' = '#FF00008B' 'LineContinuation' = '#FF000000' 'LoopLabel' = '#FF00008B' 'Member' = '#FF000000' 'NewLine' = '#FF000000' 'Number' = '#FF800080' 'Operator' = '#FFA9A9A9' 'Position' = '#FF000000' 'StatementSeparator' = '#FF000000' 'String' = '#FF8B0000' 'Type' = '#FF008080' 'Unknown' = '#FF000000' 'Variable' = '#FFFF4500' } # Generate an HTML span and append it to HTML string builder $currentLine = 1 $text = $null if ($path) { $text = (Get-Content $path) -join "`r`n" } else { Write-Error 'Please supply the path to the PowerShell script to syntax highlight as first (and only) parameter.' return } trap { break } # Do syntax parsing. $errors = $null $tokens = [system.management.automation.psparser]::Tokenize($Text, [ref] $errors) # Initialize HTML builder. $codeBuilder = new-object system.text.stringbuilder # Iterate over the tokens and set the colors appropriately. $position = 0 foreach ($token in $tokens) { if ($position -lt $token.Start) { $block = $text.Substring($position, ($token.Start - $position)) $tokenColor = 'Unknown' Get-HtmlSpan $block $tokenColor } $block = $text.Substring($token.Start, $token.Length) $tokenColor = $token.Type.ToString() Get-HtmlSpan $block $tokenColor $position = $token.Start + $token.Length } # Build the entire syntax-highlighted script $code = $codeBuilder.ToString() # Replace tabs with three blanks $code = $code -replace "\t", " " if ($WriteToPath) { # Write the HTML to a file $code | set-content -path "$path.html" } else { write-output $code } } function Get-HTMLSpan { Param ( $block, $tokenColor ) # # Original Author: Lee Holmes, http://www.leeholmes.com/blog/MorePowerShellSyntaxHighlighting.aspx # # Modified by: Helge Klein, http://blogs.sepago.de/helge/ # if (($tokenColor -eq 'NewLine') -or ($tokenColor -eq 'LineContinuation')) { if ($tokenColor -eq 'LineContinuation') { $null = $codeBuilder.Append('`') } $null = $codeBuilder.Append("<br />`r`n") } else { $block = [System.Web.HttpUtility]::HtmlEncode($block) if (-not $block.Trim()) { $block = $block.Replace(' ', ' ') } $htmlColor = $tokenColours[$tokenColor].ToString().Replace('#FF', '#') if ($tokenColor -eq 'String') { $lines = $block -split "`r`n" $block = "" $multipleLines = $false foreach ($line in $lines) { if ($multipleLines) { $block += "<BR />`r`n" } $newText = $line.TrimStart() $newText = " " * ($line.Length - $newText.Length) + $newText $block += $newText $multipleLines = $true } } $null = $codeBuilder.Append("<span style='color:$htmlColor'>$block</span>") } } Function Get-HTMLTab { [CmdletBinding()] Param ( [Parameter(Mandatory = $true, ParameterSetName = 'Open')][String] $TabName, [Parameter(Mandatory = $false, ParameterSetName = 'Open')][String]$TabHeading, [Parameter(Mandatory = $false, ParameterSetName = 'Open')][switch] $Open, [Parameter(Mandatory = $false, ParameterSetName = 'Close')][switch] $Close ) $HTML = New-GenericList -Type [string] if ($Open) { $HTML.Add('<div id="' + $TabName + '" class="tabcontent">') if (-not [string]::IsNullOrWhiteSpace($TabHeading)) { $HTML.Add("<h7>$TabHeading</h7>") } } if ($Close) { $HTML.Add('</div>') $HTML.Add(@" <script> // Get the element with id="defaultOpen" and click on it document.getElementById("defaultOpen").click(); </script> "@ ) } write-output $HTML } Function Get-HTMLTabHeader { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [Array] $TabNames ) $TabHeader = @() $TabHeader += '<ul class="tab">' $FirstTab = $true Foreach ($TabName in $TabNames) { if ($FirstTab) { $TabHeader += ' <li><a href="javascript:void(0)" class="tablinks" onclick="openTab(event, ''' + $TabName + ''')" id="defaultOpen">' + $TabName + '</a></li>' $FirstTab = $false } else { $TabHeader += ' <li><a href="javascript:void(0)" class="tablinks" onclick="openTab(event, ''' + $TabName + ''')">' + $TabName + '</a></li>' } } $TabHeader += '</ul>' Set-Variable -Scope global -Name TabHeaderCreated -Value $true Write-output $TabHeader } function Get-Parameters { Param ( $Cmdlet, [switch]$ShowCommon, [switch]$Full ) $command = Get-Command $Cmdlet -ea silentlycontinue # resolve aliases (an alias can point to another alias) while ($command.CommandType -eq "Alias") { $command = Get-Command ($command.definition) } if (-not $command) { return } foreach ($paramset in $command.ParameterSets) { $Output = @() foreach ($param in $paramset.Parameters) { if ( ! $ShowCommon ) { if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue } } $process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory, Pipeline, PipelineByPropertyName $process.Name = $param.Name if ( $param.ParameterType.Name -eq "SwitchParameter" ) { $process.Type = "Boolean" } else { switch -regex ( $param.ParameterType ) { "Nullable``1\[(.+)\]" { $process.Type = $matches[1].Split('.')[-1] + " (nullable)" ; break } default { $process.Type = $param.ParameterType.Name } } } if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" } else { $process.ParameterSet = $paramset.Name } $process.Aliases = $param.aliases if ( $param.Position -lt 0 ) { $process.Position = $null } else { $process.Position = $param.Position } $process.IsMandatory = $param.IsMandatory $process.Pipeline = $param.ValueFromPipeline $process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName $output += $process } if ( ! $Full ) { $Output | Select-Object Name, Type, ParameterSet, IsMandatory, Pipeline } else { Write-Output $Output } } } Function Get-RandomColor { <# .SYNOPSIS Random colour Function #> param( [int]$Min = 0, [int]$max = 255 ) Write-Output ([string](Get-Random -Maximum $max -Minimum $Min) + ',' ) } Function Get-RandomColorScheme { <# .SYNOPSIS Generate a colour scheme .PARAMETER $NumberOfSchemes #> param ( [Parameter(Mandatory = $false)] [int] $NumberOfSchemes = 1 ) $Hover = '0.3)' $color = '0.6)' $border = '1)' $background = '0.7)' $ColorSwing = 8 $ColorReference = Get-Random -Minimum 1 -Maximum 3 $BaseColor = (Get-Random -Maximum (200 - $ColorSwing) -Minimum (50 + $ColorSwing)) $BCMax = $BaseColor + $ColorSwing $BCMin = $BaseColor - $ColorSwing $ColorScheme = @() $i = 0 while ($i -ne $NumberOfSchemes ) { switch ($ColorReference) { 1 {$base = 'rgba(' + (Get-RandomColor -min $BCMin -max $BCMax) + (Get-RandomColor) + (Get-RandomColor) } 2 {$base = 'rgba(' + (Get-RandomColor) + (Get-RandomColor -min $BCMin -max $BCMax) + (Get-RandomColor) } 3 {$base = 'rgba(' + (Get-RandomColor) + (Get-RandomColor) + (Get-RandomColor -min $BCMin -max $BCMax) } } $Scheme = '' | select Colour, Background, Hover , Border $Scheme.Background = $base + $background $Scheme.Border = $base + $border $Scheme.Colour = $base + $color $Scheme.Hover = $base + $Hover $ColorScheme += $Scheme $i++ } Write-Output $ColorScheme } Function New-HTMLReportOptions { [CmdletBinding(DefaultParameterSetName = 'NoSave')] param ( [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [System.Collections.Hashtable] $LogoSources, [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [System.Collections.Hashtable] $ColorSchemes, [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] $CSSName = "default", [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [String] $CSSPath, [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [String] $ScriptPath, [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [String] $ColorSchemePath, [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [String] $LogoPath, [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [String]$SaveOptionsPath, [Parameter(Mandatory = $false, ParameterSetName = 'NoSave')] [Parameter(Mandatory = $false, ParameterSetName = 'Save')] [String] $ReportPath, [switch] $UseCssLinks, [switch] $UseStyleLinks ) if ($ColorSchemes -eq $null) { $ColorSchemes = Get-HTMLColorSchemes -SchemePath $ColorSchemePath } if ($LogoSources -eq $null) { $LogoSources = Get-HTMLLogos -Builtin $LogoSources += Get-HTMLLogos -LogoPath $LogoPath } $ScriptHeaderContent = New-GenericList -Type [string] if ($UseCssLinks) { $ScriptHeaderContent.Add((Get-HTMLJavaScripts -UseLinks:$UseCssLinks -ScriptPath $ScriptPath)) } else { $ScriptHeaderContent.Add((Get-HTMLJavaScripts -ScriptPath $ScriptPath)) } $StyleHeaderContent = New-GenericList -Type [string] $StyleHeaderContent.Add((Get-HTMLCSS -Builtin -UseLinks:$UseStyleLinks)) $StyleHeaderContent.Add((Get-HTMLCSS -CSSPath $CSSPath -CSSName $CSSName)) $Options = [PSCustomObject] @{ Logos = $LogoSources; ScriptContent = $ScriptHeaderContent; StyleContent = $StyleHeaderContent; ColorSchemes = $ColorSchemes; } set-variable -Name GlobalColorSchemes -Value $ColorSchemes -Scope Global if ([string]::IsNullOrEmpty($SaveOptionsPath)) { Write-Output $Options } else { Write-Verbose "Saving Report CSS to $SaveOptionsPath" $StyleHeaderContent | Set-Content -Path (Join-Path $SaveOptionsPath default.css) Write-Verbose "Saving Report Color Schemes to $SaveOptionsPath" foreach ($SchemeName in $ColorSchemes.Keys) { $ColorSchemes[$SchemeName] | ConvertTo-Csv -NoTypeInformation -Delimiter ';' | ForEach-Object {$_.Replace('"', '')} | Out-File (Join-Path $SaveOptionsPath "$schemeName.rcs") } foreach ($LogoSource in $LogoSources.keys) { [IO.File]::WriteAllBytes((Join-Path $SaveOptionsPath "$LogoSource.jpg"), [Convert]::FromBase64String($LogoSources[$LogoSource].split(',')[1])) } foreach ($CSSFile in $CSSFiles) { get-content $CSSFile.FullName | set-content (Join-Path $SaveOptionsPath $CSSFile.name) } } } Function Save-HTMLReport { <# .SYNOPSIS generation of report and invokes the file to open .PARAMETER ReportName with generate a random file name if noone is specified .PARAMETER ReportPath specifiy test directory, will use %TEMP% by default .PARAMETER ReportContent This should be the complete HTML code #> [CmdletBinding()] Param ( [Parameter(Mandatory = $false)] [string]$ReportName, [Parameter(Mandatory = $false)] [string]$ReportPath, [Parameter(Mandatory = $true)] [Array]$ReportContent, [Parameter(Mandatory = $false)] [switch]$ShowReport ) if ([string]::IsNullOrEmpty($ReportPath)) { Write-Warning "ReportPath parameter $ReportPath is empty,using Temp" $ReportPath = $env:temp } else { if ((Test-Path $ReportPath) -eq $false ) { Write-Warning "ReportPath parameter $ReportPath is not valid or can't be accessed,using Temp" $ReportPath = $env:temp } } $ReportName = $ReportName.replace('.html', '') if ($ReportName -eq $null -or $ReportName -eq "") { $ReportName = Get-RandomStringName -Size 12 } $rptFile = join-path $ReportPath ($ReportName.replace(" ", "") + ".html") Write-Verbose "Generating Report File at $rptFile" $ReportContent | Set-Content -Path $rptFile -Force Write-Verbose $rptFile if ($ShowReport) { Start-Sleep -Seconds 1 Invoke-Item $rptFile } Write-Output $rptFile } Function Set-TableRowColor { <# .SYNOPSIS adds a row colour field to the array of object for processing with htmltable .PARAMETER ArrayOfObjects The type of logo .PARAMETER Green Some additional pish .PARAMETER Yellow Some additional pish .PARAMETER Red use $this and an expression to measure the value .PARAMETER Alertnating a switch the will define Odd and Even Rows in the rowcolor column #> [CmdletBinding()] Param ( [Parameter(Mandatory = $false)] [Object[]]$ArrayOfObjects, [Parameter(Mandatory = $false)] [string]$Green = '$this -eq $false', [Parameter(Mandatory = $false)] [string]$Yellow = '$this -eq $false', [Parameter(Mandatory = $false)] [string]$Red = '$this -eq $false', [Parameter(Mandatory = $false)] [switch]$Alternating ) if ($Alternating) { $ColoredArray = $ArrayOfObjects | Add-Member -MemberType ScriptProperty -Name RowColor -Value { if ((([array]::indexOf($ArrayOfObjects, $this)) % 2) -eq 0) {'Odd'} if ((([array]::indexOf($ArrayOfObjects, $this)) % 2) -eq 1) {'Even'} } -PassThru -Force | Select-Object * } else { $ColoredArray = $ArrayOfObjects | Add-Member -MemberType ScriptProperty -Name RowColor -Value { if (Invoke-Expression $Green) {'Green'} elseif (Invoke-Expression $Red) {'Red'} elseif (Invoke-Expression $Yellow) {'Yellow'} else {'None'} } -PassThru -Force | Select-Object * } return $ColoredArray } Export-ModuleMember ` -Function @('Get-HTMLAnchor','Get-HTMLAnchorLink','Get-HTMLBarChart','Get-HTMLBarChartObject','Get-HTMLCodeBlock','Get-HTMLColumn','Get-HTMLContent','Get-HTMLContentDataTable','Get-HTMLContentTable','Get-HTMLContentTableAdvanced','Get-HTMLContentText','Get-HTMLHeading','Get-HTMLPage','Get-HTMLPieChart','Get-HTMLPieChartObject','Get-HTMLPowerShellSyntax','Get-HTMLSpan','Get-HTMLTab','Get-HTMLTabHeader','Save-HTMLReport','Set-TableRowColor') ` -Alias @('') |