Cycling through PowerShell background colors (Cycle-HostStyle)

If you have several PowerShell sessions open its easy to lose track of the purpose of each one.  One way to make this a little easier, besides having fewer PowerShell sessions open, is to assign background colors to each one.  Here’s a simple script you can add to your PowerShell startup script that will let you cycle through background colors easily.

To locate your startup script, open PowerSchell and type:

$profile

This will show the path to your startup script. Create or open that .ps1 file and then paste the Cycle-HostStyle function (at end of this post).

Next time you open a NEW PowerShell window, just run Cycle-HostStyle repeatedly until you find the color you like. The function also takes an optional number argument to set a specific color. You could also use this to automatically assign a random color to each new session.

# Updates the PowerShell host's background and foreground colors
Function Cycle-HostStyle() {
param(
# Optional specific index of the palette to change to
[Parameter(Mandatory=$false)][int]$paletteIndex=-1
)

# The colors to cycle through. The sequence of the array matters.
$palette =
@{BackgroundColor="DarkMagenta"; ForegroundColor="White"},
@{BackgroundColor="Black"; ForegroundColor="Gray"},
@{BackgroundColor="White"; ForegroundColor="Black"},
@{BackgroundColor="Magenta"; ForegroundColor="White"},
@{BackgroundColor="DarkBlue"; ForegroundColor="White"},
@{BackgroundColor="DarkGreen"; ForegroundColor="White"},
@{BackgroundColor="DarkCyan"; ForegroundColor="White"},
@{BackgroundColor="DarkRed"; ForegroundColor="White"},
@{BackgroundColor="DarkYellow"; ForegroundColor="Black"},
@{BackgroundColor="Gray"; ForegroundColor="Black"},
@{BackgroundColor="DarkGray"; ForegroundColor="White"},
@{BackgroundColor="Blue"; ForegroundColor="White"},
@{BackgroundColor="Green"; ForegroundColor="Black"},
@{BackgroundColor="Cyan"; ForegroundColor="DarkMagenta"},
@{BackgroundColor="Red"; ForegroundColor="White"},
@{BackgroundColor="Yellow"; ForegroundColor="Black"};

if($paletteIndex -lt 0) {
# Find the next paletteIndex
$curBackgroundColor = $Host.UI.RawUI.BackgroundColor;

for ($i=0; $i -le $palette.Length; $i++) {
if($palette[$i].BackgroundColor -eq $curBackgroundColor) {
$paletteIndex = $i+1;
break;
}
}
}

# Update the background and foreground, then clear the screen
$Host.UI.RawUI.BackgroundColor = $palette[$paletteIndex % $palette.Length].BackgroundColor;
$Host.UI.RawUI.ForegroundColor = $palette[$paletteIndex % $palette.Length].ForegroundColor;
cls;
}

About this entry