Skip to content

Instantly share code, notes, and snippets.

@pablitocli
Created March 27, 2018 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablitocli/815f6f3eedf091d152c9c4a6959d545b to your computer and use it in GitHub Desktop.
Save pablitocli/815f6f3eedf091d152c9c4a6959d545b to your computer and use it in GitHub Desktop.
#add-pssnapin VMware.VimAutomation.Core
#Requires -Version 2.0
Set-StrictMode -Version Latest
#Push-Location $(Split-Path $Script:MyInvocation.MyCommand.Path)
#. .\include\Export-HtmlReport.ps1
#Requires -Version 2.0
Set-StrictMode -Version Latest
Function Export-HtmlReport
{
<#
.SYNOPSIS
Creates a HTML report
.DESCRIPTION
Creates an eye-friendly HTML report with an inline cascading style sheet from given PowerShell objects and saves it to a file.
.PARAMETER InputObject
Hashtable containing data to be converted into a HTML report.
HashTable Proberties:
[array] .Object Any PowerShell object to be converted into a HTML table.
[string] .Property Select a set of properties from the object. Default is "*".
[sting] .As Use "List" to create a vertical table instead of horizontal alignment.
[string] .Title Add a table headline.
[string] .Description Add a table description.
.PARAMETER Title
Title of the HTML report.
.PARAMETER OutputFileName
Full path of the output file to create, e.g. "C:\temp\output.html".
.EXAMPLE
@{Object = Get-ChildItem "Env:"} | Export-HtmlReport -OutputFile "HtmlReport.html" | Invoke-Item
Creates a directory item HTML report and opens it with the default browser.
.EXAMPLE
$ReportTitle = "HTML-Report"
$OutputFileName = "HtmlReport.html"
$InputObject = @{
Title = "Directory listing for C:\";
Object = Get-Childitem "C:\" | Select -Property FullName,CreationTime,LastWriteTime,Attributes
},
@{
Title = "PowerShell host details";
Object = Get-Host;
As = 'List'
},
@{
Title = "Running processes";
Description = 'Information about the first 2 running processes.'
Object = Get-Process | Select -First 2
},
@{
Object = Get-ChildItem "Env:"
}
Export-HtmlReport -InputObject $InputObject -ReportTitle $ReportTitle -OutputFile $OutputFileName
Creates a HTML report with separated tables for each given object.
.INPUTS
Data object, title and alignment parameter
.OUTPUTS
File object for the created HTML report file.
.LINK
German Blog : http://www.powercli.de
English Blog: http://www.thomas-franke.net
.NOTES
NAME: Export-HtmlReport
VERSION: 1.a
AUTHOR: thomas.franke@sepago.de / sepago GmbH
LASTEDIT: 11.04.2014
#>
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline=$True, Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[Array]$InputObject,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$ReportTitle = 'Generic HTML-Report',
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[String]$OutputFileName
)
BEGIN
{
$HtmlTable = ''
}
PROCESS
{
ForEach ($InputElement in $InputObject)
{
If ($InputElement.ContainsKey('Title') -eq $False)
{
$InputElement.Title = ''
}
If ($InputElement.ContainsKey('As') -eq $False)
{
$InputElement.As = 'Table'
}
If ($InputElement.ContainsKey('Property') -eq $False)
{
$InputElement.Property = '*'
}
If ($InputElement.ContainsKey('Description') -eq $False)
{
$InputElement.Description = ''
}
$HtmlTable += $InputElement.Object | ConvertTo-HtmlTable -Title $InputElement.Title -Description $InputElement.Description -Property $InputElement.Property -As $InputElement.As
$HtmlTable += '<br>'
}
}
END
{
$HtmlTable | New-HtmlReport -Title $ReportTitle | Set-Content $OutputFileName
Get-Childitem $OutputFileName | Write-Output
}
}
Function ConvertTo-HtmlTable
{
<#
.SYNOPSIS
Converts a PowerShell object into a HTML table
.DESCRIPTION
Converts a PowerShell object into a HTML table. Then use "New-HtmlReport" to create an eye-friendly HTML report with an inline cascading style sheet.
.PARAMETER InputObject
Any PowerShell object to be converted into a HTML table.
.PARAMETER Property
Select object properties to be used for table creation. Default is "*"
.PARAMETER As
Use "List" to create a vertical table. All other values will create a horizontal table.
.PARAMETER Title
Adds an additional table with a title. Very useful for multi-table-reports!
.PARAMETER Description
Adds an additional table with a description. Very useful for multi-table-reports!
EXAMPLE
Get-Process | ConvertTo-HtmlTable
Returns a HTML table as a string.
.EXAMPLE
Get-Process | ConvertTo-HtmlTable | New-HtmlReport | Set-Content "HtmlReport.html"
Returns a HTML report and saves it as a file.
.EXAMPLE
$body = ConvertTo-HtmlTable -InputObject $(Get-Process) -Property Name,ID,Path -As "List" -Title "Process list" -Description "Shows running processes as a list"
New-HtmlReport -Body $body | Set-Content "HtmlReport.html"
Returns a HTML report and saves it as a file.
.INPUTS
Any PowerShell object
.OUTPUTS
HTML table as String
.LINK
German Blog : http://www.sepago.de/d/thomasf
English Blog: http://www.thomas-franke.net
.NOTES
NAME: ConvertTo-HtmlTable
VERSION: 1.1
AUTHOR: thomas.franke@sepago.de / sepago GmbH
LASTEDIT: 10.01.2014
#>
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline=$True, Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[PSObject]$InputObject,
[Parameter()]
[ValidateNotNullOrEmpty()]
[Object[]]$Property = '*',
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$As = 'TABLE',
[Parameter()]
[String]$Title,
[Parameter()]
[String]$Description
)
BEGIN
{
$InputObjectList = @()
If ($As -ne 'LIST')
{
$As = 'TABLE'
}
}
PROCESS
{
$InputObjectList += $InputObject
}
END
{
$ofs = "`r`n" # Set separator for string-convertion to carrige return
[String]$HtmlTable = $InputObjectList | ConvertTo-HTML -Property $Property -As $As -Fragment
Remove-Variable ofs -force
# Add description table
If ($Description)
{
$Html = '<table id="TableDescription"><tr><td>' + "$Description</td></tr></table>`n"
$Html += '<table id="TableSpacer"></table>' + "`n"
$HtmlTable = $Html + $HtmlTable
}
Else
{
$Html = '<table id="TableSpacer"></table>' + "`n"
$HtmlTable = $Html + $HtmlTable
}
# Add title table
If ($Title)
{
$Html = '<table id="TableHeader"><tr><td>' + "$Title</td></tr></table>`n"
$HtmlTable = $Html + $HtmlTable
}
# Add missing data separator tag <hr> to second column (on list-tables only)
$HtmlTable = $HtmlTable -Replace '<hr>', '<hr><td><hr></td>'
Write-Output $HtmlTable
}
}
Function New-HtmlReport
{
<#
.SYNOPSIS
Creates a HTML report
.DESCRIPTION
Creates an eye-friendly HTML report with an inline cascading style sheet for a given HTML body.
Usage of "ConvertTo-HtmlTable" is recommended to create the HTML body.
.PARAMETER Body
Any HTML body, e.g. a table. Usage of "ConvertTo-HtmlTable" is recommended
to create an according table from any PowerShell object.
.PARAMETER Title
Title of the HTML report.
.PARAMETER Head
Any HTML code to be inserted into the head-tag, e.g. scripts or meta-information.
.PARAMETER CssUri
Path to a CSS-File to be included as an inline css.
If CssUri is invalid or not provided, a default css is used instead.
.EXAMPLE
Get-Process | ConvertTo-HtmlTable | New-HtmlReport
Returns a HTML report as a string.
.EXAMPLE
Get-Process | ConvertTo-HtmlTable | New-HtmlReport -Title "HTML Report with CSS" | Set-Content "HtmlReport.html"
Returns a HTML report and saves it as a file.
.EXAMPLE
$body = Get-Process | ConvertTo-HtmlTable
New-HtmlReport -Body $body -Title "HTML Report with CSS" -Head '<meta name="author" content="Thomas Franke">' -CssUri "stylesheet.css" | Set-Content "HtmlReport.html"
Returns a HTML report with an alternative CSS and saves it as a file.
.INPUTS
HTML body as String
.OUTPUTS
HTML page as String
.LINK
German Blog : http://www.sepago.de/d/thomasf
English Blog: http://www.thomas-franke.net
.NOTES
NAME: New-HtmlReport
VERSION: 1.1
AUTHOR: thomas.franke@sepago.de / sepago GmbH
LASTEDIT: 10.01.2014
#>
[CmdletBinding()]
Param(
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$CssUri,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$Title = 'HTML Report',
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$Head = '',
[Parameter(ValueFromPipeline=$True, Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[Array]$Body
)
# Add title to head because -Title parameter is ignored if -Head parameter is used
If ($Title)
{
$Head = "<title>$Title</title>`n$Head`n"
}
# Add inline stylesheet
If (($CssUri) -And (Test-Path $CssUri))
{
$Head += "<style>`n" + $(Get-Content $CssUri | ForEach {"`t$_`n"}) + "</style>`n"
}
Else
{
$Head += @'
<style>
table
{
Margin: 0px 0px 0px 4px;
Border: 1px solid rgb(190, 190, 190);
Font-Family: Tahoma;
Font-Size: 8pt;
Background-Color: rgb(252, 252, 252);
}
tr:hover td
{
Background-Color: rgb(150, 150, 220);
Color: rgb(255, 255, 255);
}
tr:nth-child(even)
{
Background-Color: rgb(242, 242, 242);
}
th
{
Text-Align: Left;
Color: rgb(150, 150, 220);
Padding: 1px 4px 1px 4px;
}
td
{
Vertical-Align: Top;
Padding: 1px 4px 1px 4px;
}
#TableHeader
{
Margin-Bottom: -1px;
Background-Color: rgb(255, 255, 225);
Width: 30%;
}
#TableDescription
{
Background-Color: rgb(252, 252, 252);
Width: 30%;
}
#TableSpacer
{
Height: 6px;
Border: 0px;
}
</style>
'@
}
$HtmlReport = ConvertTo-Html -Head $Head
# Delete empty table that is created because no input object was given
$HtmlReport = $($HtmlReport -Replace '<table>', '') -Replace '</table>', $Body
Write-Output $HtmlReport
}
##CONEXION VCENTER SERVER
$vcenter= read-host "vCenter Server Name"
$cred= get-credential
connect-viserver $vcenter -credential $cred
$fecha= get-date -format "ddMMyyyy"
write-host "###############################################################" -foregroundcolor BLUE
##VARIABLES!!
$OutputFileName = "Infra.html"
$ReportTitle = "Inventario basico de Infraestructura VMWare - By PablitoCLI"
$Propsd = @()
$Propsrecuros = @()
$Resultsresc = @()
$Resultsstore = @()
$propvmcluster = @()
$ResultsrVMCLUSTER = @()
$propvmdrs = @()
$ResultsrVMdrs = @()
$Resultshost = @()
$Propsh = @()
$drsvmexceptions= @()
$VMConfigxCluster= @()
##CSV DE SALIDA
$outputstore = "CompletoESXi.csv"
##RECOPILACIÓN DE INFORMACION
$dcenters=get-datacenter
####COMIENZO INVENTARIO DATASTORES!!!
write-host "############# INVENTARIO DATASTORE ###################" -foregroundcolor green
foreach ($dcenter in $dcenters)
{
write-host "############# INVENTARIANDO DATACENTER <"$Dcenter"> ###################" -foregroundcolor green
$clusters=get-datacenter $dcenter | get-cluster
$x=100
$porc=0
foreach($cluster in $clusters)
{
Write-Host "Recolectando informacion del cluster : <"$cluster.Name"> "
$recursos= $cluster | get-vmhost
$memusada=0
$memtotal=0
foreach ($recurso in $recursos){
$memusada+= $recurso.MemoryUsageGB
$memtotal+= $recurso.MemoryTotalGB
}
$porc= ($memusada * 100) / $memtotal
if ($porc -le $x) {
$x=$porc
$dis= $cluster.name
}
$isolation= $cluster.HAIsolationResponse
$canthost=$cluster.ExtensionData.Summary.numhosts
$cant_host_ok=$cluster.ExtensionData.Summary.NumEffectiveHosts
$admisioncontrol=$cluster.HAAdmissionControlEnabled
$restartprioridad=$cluster.HARestartPriority
$swapconfig=$cluster.VMSwapfilePolicy
$vmmonitoring=$cluster.ExtensionData.Configuration.dasconfig.vmmonitoring
$hostmonitoring=$cluster.ExtensionData.Configuration.dasconfig.hostmonitoring
$hbdatastore=$cluster.ExtensionData.Configuration.DasConfig.HeartbeatDatastore
$drsagresividad=$cluster.ExtensionData.Configuration.DrsConfig.VmotionRate
$drsvmexceptions=$cluster.ExtensionData.Configuration.drsvmconfig
$hbadata=""
$i=$hbdatastore.count
for($j=0; $j -lt $i; $j++){
foreach ($data in ($cluster | get-vmhost | get-random | get-datastore)){
$idx=$data.ExtensionData.MoRef.value
$datahb=$hbdatastore.value[$j]
if ($datahb -eq $idx){
$hbadata+= $data.name
$hbadata+=";"
}
}
}
$VMConfigxCluster=$cluster.ExtensionData.Configuration.DasVmConfig
$Propsrecuros = @{
Cluster=$cluster.Name
HA_Estado= $cluster.HAEnabled
HA_NIVEL= $Cluster.HAFailoverLevel
DRS_Estado= $cluster.DrsEnabled
DRS_Nivel= $cluster.DrsAutomationLevel
DRS_AGRESIVIDAD=$drsagresividad
ISOLATION= $isolation
ADMISSION_CONTROL= $admisioncontrol
RESTART_PRIORITY= $restartprioridad
SWAP_CONFIG=$swapconfig
DATASTORE_HEARTBEAT=$hbadata
CANTIDAD_HOST=$canthost
CANTIDAD_HOST_OK=$cant_host_ok
MemoriaTotal="{0:n2}" -f $Memtotal
MemoriaUsada= "{0:n2}" -f $Memusada
"Porcentaje de Uso"= "{0:n2}" -f $porc
}
$Resultsresc += New-Object PSObject -Property $Propsrecuros
#### CONFIGURACIONES DE LAS VMS PARA EVENTOS DE HA ####
Foreach ($VMconfig in $VMConfigxCluster){
$vmid=$VMconfig.key.type+"-"+$VMconfig.key.value
$v=get-vm | where {$_.id -eq $vmid}
$restartpriority=$VMconfig.DasSettings.RestartPriority
$vmisolate=$VMconfig.DasSettings.IsolationResponse
$propvmcluster = @{
CLUSTER=$Cluster.name
SERVIDOR=$v.name
RESTART_PRORITY=$restartpriority
VM_ISOLATE=$vmisolate
}
$ResultsrVMCLUSTER += New-Object PSObject -Property $propvmcluster
}
#### EXCEPSIONES DE DRS EN EL CLUSTER ####
if ($drsvmexceptions -eq $null)
{
$propvmdrs = @{
SERVIDOR="NO HAY EXCEPSIONES DE VMOTIONS PARA VMs EN EL CLUSTER "
}
$ResultsrVMdrs += New-Object PSObject -Property $propvmdrs
}
else
{
Foreach ($drsvms in $drsvmexceptions){
$vmidx=$drsvms.key.type+"-"+$drsvms.key.value
$v= get-vm | where {$_.id -eq $vmidx}
$drsvmotion=$drsvms.Enabled
$drsvmotionstate=$drsvms.Behavior
$propvmdrs = @{
SERVIDOR=$v.name
DRS_VMOTION=$drsvmotion
DRS_CONFIG=$drsvmotionstate
}
$ResultsrVMdrs += New-Object PSObject -Property $propvmdrs
}
}
write-host "############# INVENTARIANDO CLUSTER <"$CLUSTER"> ###################" -foregroundcolor green
foreach ($vmhost in get-cluster $cluster | get-vmhost)
{
Write-Host "Recolectando informacion del host: <"$vmhost.Name"> "
$info= get-vmhost $vmhost
$v=$info | get-view
$serial=$v.Hardware.SystemInfo.OtherIdentifyingInfo | where {$_.IdentifierType.Key -eq "ServiceTag"}
$biosversion=$v.hardware.biosinfo.biosversion
$biosdate=$v.hardware.biosinfo.releasedate
$mem= $info.memorytotalGB
$usadamem=$info.MemoryUsageGB
$porc= ( $info.MemoryUsageGB * 100 ) / $info.memorytotalGB
$gnic= get-vmhostnetworkadapter -vmhost $vmhost -name vmk0
$Services= $info | get-vmhostservice
$ntpservices= $services | where {$_.key -eq "ntpd"}
$SSHservices= $services | where {$_.key -eq "TSM"}
$SHELLservices= $services | where {$_.key -eq "TSM-SSH"}
$ntp= Get-VMHostNtpServer -VMHost $vmhost
$ntpserver= $ntp -join ", "
get-vmhost $vmhost | %{$dts = get-view $_.ExtensionData.configManager.DateTimeSystem}
#get host time
$time = $dts.QueryDateTime().tolocaltime()
#calculate time difference in secconds
$timedife = ( $time - [DateTime]::Now).TotalSeconds
$nexus=get-vmhost $vmhost | Get-VirtualPortGroup -Distributed
if ($nexus -eq $null)
{
$na="NO"
$nombre_nexus="NO TIENE"
$des_nexus="NO TIENE"
$vds="NO TIENE"
}
else
{
$na="SI"
$nombre_nexus= get-vmhost $vmhost | Get-VirtualPortGroup -Distributed | select virtualswitch | select-object -index 1
$vds= $info | Get-VirtualSwitch -name $nombre_nexus.virtualswitch
$des_nexus=$vds.ExtensionData.Summary.Description
}
$vsw=$info | get-vmhostnetworkadapter -name vmnic*
$vnics=$vsw.name
foreach ($vnic in $vnics)
{
$esxcli=get-vmhost $vmhost | get-view
$nic= $info | get-vmhostnetworkadapter -name $vnic
$vnic_pci=$nic.ExtensionData.Pci
$data=$esxcli.Hardware.PciDevice | where { $_.id -like $vnic} | select VendorName, DeviceName
$nic=get-vmhost $vmhost | ? { $_.Version -gt 5} | get-esxcli | select @{N="HostName"; E={$_.system.hostname.get().FullyQualifiedDomainName}},@{N="Driver";E={$_.network.nic.get($vnic).DriverInfo.Driver}},@{N="Firmware";E={$_.network.nic.get($vnic).DriverInfo.FirmwareVersion}},@{N="DriverVersion";E={$_.network.nic.get($vnic).DriverInfo.Version}}
}
$hbas=Get-VMHostHba -vmhost $vmhost -type "FibreChannel" | select model, status
if ($hbas -eq $null)
{$hba_model="NO PRESENTA PLACAS HBA"
$hba_status="NO PRESENTA PLACAS HBA"
$qdhba="SIN VALOR"
}
else
{
foreach ($hba in $hbas)
{
$hba_model=$hba.model
$hba_status=$hba.status
$esxcli = Get-EsxCli -VMHost $vmhost
if($hba_model -like "Brocade*") {$qdhba= $esxcli.system.module.parameters.list("bfa") | where {$_.Name -eq "bfa_lun_queue_depth"}}
ELSE {$qdhba= $esxcli.system.module.parameters.list("qlnativefc") | where {$_.Name -eq "ql2xmaxqdepth"}}
if ($qdhba.value -eq "") {$qdhba="SIN VALOR"} else {$qdhba=$qdhba.value}
}
}
$Propsh = @{
DATACENTER= $dcenter
CLUSTER = $cluster.name
HOST = $vmhost
IP = $gnic.ip
MODELO=$info.model
SERIAL=$serial.IdentifierValue
BIOS_VERSION=$biosversion
BIOS_FECHA=$biosdate
VERSION=$info.version
BUILD=$info.build
CPU=$info.processortype
CORES=$info.numcpu
MEMORIA= "{0:N2}" -f $mem
MEMORIA_USADA= "{0:N2}" -f $usadamem
MEMORIA_PORC= "{0:N2}" -f $porc
HORA_EQUIPO=$time
DIFERENCIA_TIEMPO= "{0:N2}" -f $timedife
NTP_SERVER=$ntpserver
NTP_POLITICA=$ntpservices.policy
NTP_ESTADO=$ntpservices.running
SSH_POLITICA=$SSHservices.policy
SSH_ESTADO=$SSHservices.running
ESX_SHELL_POLITICA=$SHELLservices.policy
ESX_SHELL_ESTADO=$SHELLservices.running
TIENE_DVS=$na
DVS=$vds
DVS_MODELO=$des_nexus
VMNIC_Driver=$nic.driver
VMNIC_Firmware=$nic.firmware
VMNIC_DriverVersion=$nic.driverversion
HBA_MODEL=$hba_model
HBA_STATUS=$hba_status
QUEUDEPTH=$qdhba
}
$Resultshost += New-Object PSObject -Property $Propsh
}
$nic=0
$na=""
$nombre_nexus=""
$des_nexus=""
}
}
###########################################################################################################################
$InputObject = @{
Title= "Configuración y Recursos de los Clusters";
Object = $Resultsresc | Select-object Cluster, HA_Estado, HA_NIVEL, DRS_Estado, DRS_Nivel, DRS_AGRESIVIDAD, ISOLATION, ADMISSION_CONTROL, RESTART_PRIORITY, SWAP_CONFIG, DATASTORE_HEARTBEAT,CANTIDAD_HOST, CANTIDAD_HOST_OK, MemoriaTotal, MemoriaUsada, "Porcentaje de Uso"
},
@{
Title= "Configuración de las VMs para Eventos de HA";
Object = $ResultsrVMCLUSTER | Select-object Cluster, SERVIDOR, RESTART_PRORITY,VM_ISOLATE
},
@{
Title= "Inventario y configuración de los HOST ESXI de la Infraestructura";
Object = $Resultshost | Select-object DATACENTER, CLUSTER, HOST, IP, MODELO, SERIAL, BIOS_VERSION, BIOS_FECHA, VERSION, BUILD, CPU, CORES, MEMORIA, MEMORIA_USADA, MEMORIA_PORC, HORA_EQUIPO, DIFERENCIA_TIEMPO, NTP_SERVER, NTP_POLITICA, NTP_ESTADO, SSH_POLITICA, SSH_ESTADO, ESX_SHELL_POLITICA, ESX_SHELL_ESTADO, TIENE_DVS, DVS, DVS_MODELO, VMNIC_Driver, VMNIC_Firmware, VMNIC_DriverVersion, HBA_MODEL, HBA_STATUS, QUEUDEPTH
},
@{
Title= "Excepsiones de DRS del cluster";
Object = $ResultsrVMdrs
}
Export-HtmlReport -InputObject $InputObject -ReportTitle $ReportTitle -OutputFile $OutputFileName
Invoke-Item $OutputFileName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment