Skip to content Skip to sidebar Skip to footer

Formatting Columns Of Html Output Depending On Their Value

I'm trying to apply conditional formatting to the output of a simple PowerShell function: function Get-RamInfo { $os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName

Solution 1:

The problem is that once you have converted object to HTML you wont be able to use if/else statemnet to its properties. I have edited your script a little. It should work now.

function Get-RamInfo {
    $os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computername
    $cs = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computername
    $memcalc = ($cs.totalphysicalmemory / 1GB) - ($os.freephysicalmemory / 1MB)
    $calc = ($os.freephysicalmemory / 1MB) / ($cs.totalphysicalmemory / 1GB) * 100 -as [int]

    $props = [ordered]@{'Total RAM (GB)'="{0:N2}" -f ($cs.totalphysicalmemory / 1GB);
        'Total RAM In Use (GB)'="{0:N2}" -f ([math]::Round($memcalc,2));
        'Total RAM Available (GB)'="{0:N2}" -f ($os.freephysicalmemory / 1MB);
        'Total Ram Available (%)'= $calc;
    }

    $obj = New-Object -TypeName PSObject -Property $props

    Write-Output $obj
}

$raminfo = Get-RamInfo -ComputerName $computername  | 
                Select -Property *,@{
                                         name='class';e={
                                             if ($_.'Total Ram Available (%)' -lt20){'<tr class="warning">'}
                                             elseif ($_.'Total Ram Available (%)' -lt10){'<tr class="danger">'}
                                             else{'<tr>'}
                                         }
                                     }

$frag3 = $raminfo | Select 'Total RAM (GB)','Total RAM In Use (GB)','Total RAM Available (GB)','Total Ram Available (%)' | 
         ConvertTo-Html -As Table -Fragment -PreContent '<h2>Memory Info</h2>' |
            foreach { $_ -replace '<tr>',$($raminfo.class)
            } | Out-String

Solution 2:

At the point where your if statement sees the data you don't have the objects and properties that you're trying to check anymore. Use a regular expression and a switch statement instead to extract the numeric values from the HTML string:

$re = '<tr>(<td>[0-9.]+?</td><td>[0-9.]+?</td><td>([0-9.]+?)</td>)'

... | ForEach-Object {
  if ($_ -match$re) {
    switch ([int]$matches[2]) {
      {$_ -lt 20} { $_ -replace $re, '<tr class="warning">$1' }
      {$_ -lt 10} { $_ -replace $re, '<tr class="critical">$1' }
      default     { $_ }
    }
  }
} | ...

Post a Comment for "Formatting Columns Of Html Output Depending On Their Value"