Is my code a Cleaner code?

Hi Guys,

I’m looking at the best way to display WMI information which will be in a HTML report but which In I have the minimal code required. See Below what I have. I’m pulling data from 4 WMI objects. Thanks

Write-Output “*Collecting System Information”

try
{

#Get WMI Objects using CIM

$cs = Get-CimInstance -ClassName win32_computersystem -ComputerName $ComputerName -ErrorAction Stop
$os = Get-CimInstance -ClassName Win32_operatingsystem -ComputerName $ComputerName -ErrorAction Stop
$bs = Get-CimInstance -ClassName win32_bios -ComputerName $ComputerName -ErrorAction Stop
$power = Get-CimInstance -Namespace root\cimv2\power -Class win32_PowerPlan | Where-Object {$_.IsActive -eq “True”}|Select ElementName -ErrorAction Stop
$powerplan = if ($OSPower.ElementName -notlike “*Performance”) {"$($OSPower.ElementName)(Recommended Plan: High Performance)"}
else {$OSPower.ElementName}

$csinfo = @()
$csinfoObj = New-Object PSObject

$csinfoObj | Add-Member -Name ‘Name’ -MemberType NoteProperty -Value $cs.Name
$csinfoObj | Add-Member -Name ‘System Uptime’ -MemberType NoteProperty -Value $cs.AdminPasswordStatus
$csinfoObj | Add-Member -Name ‘Serial Number’ -MemberType NoteProperty -Value $bs.SerialNumber
$csinfoObj | Add-Member -Name ‘Operating System’ -MemberType NoteProperty -Value $os.Caption
$csinfoObj | Add-Member -Name ‘Last Boot’ -MemberType NoteProperty -Value $os.LastBootUpTime
$csinfoObj | Add-Member -Name ‘Domain Connected’ -MemberType NoteProperty -Value $cs.PartOfDomain
$csinfoObj | Add-Member -Name ‘OS Architecture’ -MemberType NoteProperty -Value $os.OSArchitecture
$csinfoObj | Add-Member -Name ‘Power Plan’ -MemberType NoteProperty -Value $powerplan

$csinfo += $csinfoObj

$SystemInfoHTML += $csinfo | ConvertTo-Html -Fragment -As List -PreContent “

System Information
” | ForEach {$_ -replace “”,"<table class=“list”>"}
}
catch
{
Write-Warning $.Exception.Message
$htmlbody += "<p>An error was encountered. $($.Exception.Message)</p>"
$htmlbody += $spacer
}

IMO, as a standalone script. This looks okay.

Agree code looks ok, but I have a question and maybe a couple suggestions.

  1. It looks like you are referencing a variable $OSPower but I never see it defined. I see an $os and a $power defined but no $OSPower.
  2. When you define $power you don’t pass a -computername argument which means it will return data from the current host. Is this intentional?
  3. If you are always passing -computername $ComputerName and -ErrorAction Stop, you might want to consider using splatting to make it more concise.
  4. What version of PowerShell are you running? If 3.1 or later, I’d recommend using the [pscustomobject] type accelerator with a hashtable to create your custom object. It just looks a little cleaner.

On point 4 it also seems to have a performance increase from what I have seen running some very large scripts in both ways!