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
[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-NullDespué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
- Diversión del viernes: un cosquilleo de PowerShell
- Diversión del viernes: ver objetos en una GridList de PowerShell
- Diversión del viernes: ¡Es PowerShell, cariño!
- Diversión del viernes: obtenga el día del año con PowerShell
- Viernes divertido: cree una ventana de seguimiento de PowerShell
- Viernes 13 Diversión PowerShell
- Viernes divertido: busque el proceso de bloqueo de archivos con PowerShell
- Viernes divertido: cree todos los scripts de perfil de PowerShell
- Friday Fun: una consola PowerShell aleatoria
- Viernes divertido PowerShell inverso
- Texto divertido del viernes a HTML
- Diversión del viernes: creación de scripts de PowerShell con PowerShell
- Diversión del viernes: arriésgate con PowerShell
- Diversión del viernes: envíe contenido de PowerShell ISE a Word
- Viernes divertido: abra el último archivo en PowerShell ISE

