Búsqueda de sitios web

Diversión del viernes: 50 sombras de informes HTML de PowerShell


Siempre estoy buscando formas de agregar refuerzo visual a mis informes HTML. Y dado que realizar un seguimiento del espacio en disco es una tarea común de los profesionales de TI, pensé que sería bueno tener una representación visual de la utilización del disco. Así que creé un breve script de prueba de concepto que genera un informe HTML como este:

¿Qué opinas? Así es como lo hice.

#requires -version 3.0

<#
proof of concept using an HTML gradient.
#>

[cmdletbinding()]
Param(
[string]$Computername=$env:computername,
[string]$ReportTitle="Drive Utilization Report",
[string]$Path="$env:temp\utilization.htm"
)

#define HTML header with style elements
$head = @'
<style>
body { background-color:#FFFFFF;
       font-family:Calibri;
       font-size:12pt; }
td, th { border:0px solid black; 
         border-collapse:collapse; }
th { color:white;
     background-color:black; }
table, tr, td, th { padding: 2px; margin: 0px }
tr:nth-child(odd) {background-color: lightgray}
table {
width:95%;
margin-left:10px; 
margin-bottom:20px;
}
caption 
{
background-color:#FFFF66;
text-align:left;
font-weight:bold;
font-size:14pt;
}
</style>
'@

 <#
 Define a here string for coloring percentage cells.
 The starting and ending percents will need to provided
 using the -f operator.
 #>
$gradient=@"
filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, 
StartColorStr=#0A802D, EndColorStr=#FF0011)
background-color: #376C46;
background-image: -mso-linear-gradient(left, #0A802D {0}%, #FF0011 {1}%);
background-image: -ms-linear-gradient(left, #0A802D {0}%, #FF0011 {1}%);
background-image: -moz-linear-gradient(left, #0A802D {0}%, #FF0011 {1}%);
background-image: -o-linear-gradient(left, #0A802D {0}%, #FF0011 {1}%);
background-image: -webkit-linear-gradient(left, #0A802D {0}%, #FF0011 {1}%);
background-image: linear-gradient(left, #0A802D {0}%, #FF0011 {1}%);
"@

#define an array to hold HTML fragments
$fragments=@()

#get the data for the report
$data = Get-CimInstance Win32_logicaldisk -filter "drivetype=3" -ComputerName $computername

#Create a custom object for each drive
$drives = foreach ($item in $data) {
    $prophash = [ordered]@{
    Drive = $item.DeviceID
    Volume = $item.VolumeName
    SizeGB = $item.size/1GB -as [int]
    FreeGB = "{0:N4}" -f ($item.Freespace/1GB)
    PercentFree = [math]::Round(($item.Freespace/$item.size) * 100,2)
    }
    New-Object PSObject -Property $prophash
} #foreach item

#convert drive objects to HTML but as an XML document
[xml]$html = $drives | ConvertTo-Html -Fragment

#add the computer name as the table caption
$caption= $html.CreateElement("caption")                                                                     
$html.table.AppendChild($caption) | Out-Null                                                                            
$html.table.caption= $data[0].SystemName

#go through rows again and add gradient
for ($i=1;$i -le $html.table.tr.count-1;$i++) {
  $class = $html.CreateAttribute("style")
  [int]$start = $html.table.tr[$i].td[-1]
  #create the gradient using starting and ending values
  #based on %free
  $class.value = $Gradient -f $start,(100-$start)
  $html.table.tr[$i].ChildNodes[4].Attributes.Append($class) | Out-Null
} #for

#add the html to the fragments
$fragments+= $html.InnerXml

#include a footer
$fragments+="<I>Report run $(Get-Date)</I>"

#create the final report
ConvertTo-HTML -head $head -title $reportTitle -PreContent "<h1>Drive Utilization</h1>" -PostContent $fragments |
Out-File -FilePath $path -Encoding ascii

El elemento clave aquí es la adición de un degradado. En el script puedes ver que he definido una cadena aquí para el degradado. La cadena incluye código para admitir casi cualquier navegador, es por eso que ves todas las líneas de imagen de fondo. La cadena aquí también tiene marcadores de posición, {0} y {1} para los porcentajes inicial y final. Explicaré cómo funciona eso en un momento.

Al utilizar Get-CIMInstance, el script obtiene discos lógicos fijos. Ahora, en lugar de simplemente crear un fragmento HTML, lo creo como un documento XML. Esto me permite agregar un título a la tabla, usando el nombre de la computadora. Luego repito el nodo de la tabla, omitiendo la primera fila que es el encabezado de la tabla. Creo un atributo llamado Estilo.

for ($i=1;$i -le $html.table.tr.count-1;$i++) {
  $class = $html.CreateAttribute("style")
...

A continuación, obtengo el valor de la última celda , que es el valor de PercentFree. Esa es una de las razones por las que utilicé una tabla hash ordenada para poder garantizar que la última celda siempre sería la propiedad PercentFree. Tomo el valor y me aseguro de que sea un número entero.

[int]$start = $html.table.tr[$i].td[-1]

Puedo usar este valor y conectarlo a mi cadena de gradiente aquí usando el operador -f.

$class.value = $Gradient -f $start,(100-$start)

Agrego el atributo de estilo a cada nodo. Esto me permite establecer diferentes valores para cada unidad.

$html.table.tr[$i].ChildNodes[4].Attributes.Append($class) | Out-Null

Después de revisar las filas de la tabla, todo lo que queda es agregar el HTML modificado, que es la propiedad InnerXML, a mi conjunto de fragmentos y crear el informe final.

El gradiente no es absoluto, pero le brinda una aproximación visual aproximada de cuánto espacio libre hay en cada unidad. Por cierto, también puedes utilizar el degradado en el elemento del cuerpo de una hoja de estilo si quieres darle vida al fondo de tu informe.

Incluí muchos comentarios en mi código que espero ayuden. Si no, por favor deja un comentario. ¡Disfrutar!

Artículos relacionados