Thursday, December 10, 2015

Format table color style odd even rows Powershell

Format table row colors Inovation Powershell Version 2

Yesterday while trouble shooting some processes using Get-Process command, While viewing the results on powershell console I had trouble to locate row, I was not able to concentrate on single row in hurry. Each row I had to look carefully by moving my mouse because sometimes i was incorrectly taking values from incorrect row (upper or down), And that time I got idea struck into my mind, what if there is possibility to color the odd and even rows differently, formatting table in odd even color.

This is the script I have written to solve my problem. I hope it will be useful to you as well.
###########################Script Starts here##################################
function Format-OddEven {
    $input | foreach {
        $Number = [array]::IndexOf($ProcessData, $_)
        $ConsoleBack = [System.Console]::BackgroundColor
        $ConsoleFore = [System.Console]::ForegroundColor
        if (($Number % 2) -eq 0) {
            [System.Console]::BackgroundColor = "DarkGray"
            [System.Console]::ForegroundColor = "black"
            $_
        } #if
        else {
            [System.Console]::BackgroundColor = $ConsoleBack
            [System.Console]::ForegroundColor = $ConsoleFore
            $_
        } #else
        [System.Console]::BackgroundColor = $ConsoleBack
        [System.Console]::ForegroundColor = $ConsoleFore
    } #input
<#
.Synopsis
Format table output row odd even colors.
.Example
Get-Service | Format-OddEven
.Notes
    NAME:  Format-OddEven
    AUTHOR: Kunal Udapi
    LASTEDIT: 10 Decemeber 2015
    KEYWORDS: Format Table color
.Link
Check Online version: Http://kunaludapi.blogspot.com
#>
} #function Format-OddEven

###########################Script ends here##################################
Screenshot of result:
How do you use this script for daily use? set it in Powershell profile.
Under Documents in your User Profile create folder WindowsPowerShell, and in this folder create file Microsoft.PowerShell_profile.ps1 (If you already have this folder and file Edit it), Open the file and copy paste above code, save file. relaunch Powershell, now this profile will be loaded each time you open PowerShell. (Make sure executionpolicy is set to bypass or remotesigned)
Store your table in variable, Variable name should be always $processdata (I will work on it once get time)
$processdata =  Get-Process
$processdata | Formate-OddEven
Instead of Get-Process you can use other command as well, ie Get-Service.

No comments: