Making Reports in PowerShell (Part 3 of 3)

In Part 1, I showed you a common approach to making text-based reports in PowerShell. In Part 2, I made some improvements to bring the technique more in line with better PowerShell practices. Now, I'll show you how I really like to do these things.


[CmdletBinding()]
param (
    [Parameter(Mandatory=$True)]
    [string]$computername
)

function CSInfo {
    param($computername)
    $cs = Get-WmiObject -Class Win32_ComputerSystem -computername $computername
    $bios = Get-WmiObject -class Win32_BIOS -computername $computername
    $props = @{'Computer'=$cs.name;
               'Manufacturer'=$cs.manufacturer;
               'Model'=$cs.model;
               'BIOSSerial'=$bios.serialnumber}
    $obj = New-Object -TypeName PSObject -Property $props
    Write-Output $obj
}

$html = "<h3>COMPUTER SYSTEM</h3>"
$html += CSInfo -computername $computername |
ConvertTo-HTML -Fragment

$html += "<h3>OPERATING SYSTEM</h3>"
$html += Get-WmiObject -Class Win32_OperatingSystem -computername $computername |
Select-Object -Property Version,BuildNumber,ServicePackMajorVersion,OSArchitecture |
ConvertTo-HTML -Fragment

$html += "<h3>PROCESSORS</h3>"
$html += Get-WmiObject -class Win32_Processor  -computername $computername |
Select-Object -Property AddressWidth,MaxClockSpeed -First 1 |
ConvertTo-HTML -Fragment

$html += "<h3>DISKS</h3>"
$html += Get-WmiObject -class Win32_LogicalDisk -filter "drivetype=3" -computername $computername |
Select-Object -Property DeviceID,Size,FreeSpace |
ConvertTo-HTML -Fragment

$formatting = "<STYLE>table,td,th {border:thin black solid;} h2 {margin-top:12pt;}</STYLE>"

ConvertTo-HTML -Body $html -Head $formatting

Save this as C:\Report.ps1 and then run it like this:



C:\Report | Out-File Inventory.html
By letting PowerShell convert each section of the report to an HTML fragment, I can then combine them together. You'll see where I applied some simple CSS formatting to the final product to dress it up a bit - you could get pretty wild with that. I didn't include the out-File in the script, because sometimes I don't want this in a file - I want it in an e-mail, or someplace else, so my script doesn't worry about the final product.


I love reports like this because they're nicely-formatted, and require very little work on my part to format them.

So what do you think? What kinds of reports might you create this way? What other report-generating techniques can you share? Let me know at my new online Q&A forum!

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×