Formatting powershell output with colours

Reading Kunal Udapi post about painting odd and even rows with different colours gave me the idea to highlight rows that met a condition.
I needed very little changes to his script to approach my needs.

get-service|format-highlight status stopped magenta

function Format-highlight {
    param ($param,$value,$color)

    begin {

        $ConsoleBack = [System.Console]::BackgroundColor
        $ConsoleFore = [System.Console]::ForegroundColor
        $RowColors = @(
            @{
                Back = $ConsoleBack
                Fore = $color
            },
            @{
                Back = $ConsoleBack
                Fore = $ConsoleFore
            }
        )
    }
    process {

        # $Index will be either 0 or 1 and used to pick colors from $RowColors
        if ($_.$param -eq $value){$index=0}else{$index=1}
        [System.Console]::BackgroundColor = $RowColors[$Index].Back
        [System.Console]::ForegroundColor = $RowColors[$Index].Fore
        $_
    }
    end {
        [System.Console]::BackgroundColor = $ConsoleBack
        [System.Console]::ForegroundColor = $ConsoleFore
    }

} #function Format-highlight
Remember to add this function to your powershell profile at %userprofile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 to have it always available.

Comments

  1. Great I happy, My scripts are getting useful day by day. Keep it up.

    ReplyDelete

Post a Comment