Home > Blockchain >  Powershell Different color in strings with echo in array
Powershell Different color in strings with echo in array

Time:09-01

I trying to write a script, which show iis pools state with a different color. And I can't understand why script coloring in one color all strings when I use echo. Here script:

    $pools = invoke-command -session $session -scriptblock {Import-Module WebAdministration; Get-ChildItem IIS:\AppPools | Where {$_.Name -like "*abc*"}}
    $poolsShow = $pools | Select-Object -Property name, state
    $poolsShow | ForEach-Object {
        if($_.state -eq "Started") { 
            $Host.UI.RawUI.ForegroundColor = "Green";
            echo $_;
            [Console]::ResetColor();
        }
        if($_.state -eq "Stopped") { 
            $Host.UI.RawUI.ForegroundColor = "Red";
            echo $_;
            [Console]::ResetColor();
        }
    }

It is work if I go through the $pools, but if I select name and state via Select-Object - all strings are coloring in the color of the last service. I have tried via Write-Host - and it's worked, but I didn't find a way, how to format output in one table with a headers only at first line and with the same width in every string.

CodePudding user response:

You can take a similar approach as the one proposed in demo

CodePudding user response:

To complement screenshot

Add -WholeLine if you want to color matching lines in full.

  • The hashtable maps search text patterns to colors.

  • Whenever a pattern is found in the formatted representations of the input objects, it is colored using the specified color.

    • Note that this means that finding what to color is purely based on string parsing, not on OOP features (such as checking specific properties).
  • Note that the hashtable keys are regexes by default, unless you also specify -SimpleMatch.

    • Thus you could easily make the above more robust, if needed, such as replacing Started = with '\bStarted\b' = in order to only match full words.
  • Related