0
votes

I am trying to find a way to make Format-Table output selected rows in red and others in green.

An example that I am trying to do is output the current processes and the amount of memory they are using. I want to apply logic to the output so that processes using above a given amount of memory will be displayed in yellow and others that are even higher displayed in red.

The closest question I have found is: Color words in powershell script format-table output

How can I extract the numbers from the string to process them?

1

1 Answers

0
votes

In Powershell it is generally easier to work with objects that are not strings. In this example, however, you have to use the write-host cmdlet, because it is the only cmdlet that generates colored output to the console. But write-host doesn't format objects the way most cmdlets would (using the format.ps1xml files), so to get the expected format you pipe the process objects to out-string. However out-string includes column headers and a blank line before every row (remove the substring() call to see what I mean). So the substring(244,80) is a bit of a hack to just get the actual process info.

gps | % {
  $line = ($_|out-string).substring(244,80)
  if ($_.ws -lt 100MB) {
    write-host $line
  } elseif ($_.ws -lt 150MB) {
    write-host $line -foregroundcolor yellow
  } else {
    write-host $line -foregroundcolor red
  }
}