Skip to content

Instantly share code, notes, and snippets.

@diogotito
Created January 17, 2024 19:37
Show Gist options
  • Save diogotito/55584d417e624e8681d77042cd61b7f4 to your computer and use it in GitHub Desktop.
Save diogotito/55584d417e624e8681d77042cd61b7f4 to your computer and use it in GitHub Desktop.
Powershell utility functions in $profile to easily colorize things in Calculated Properties (for Select-Object, Format-Table, etc.)
# aux
# ---------------------
enum CC { RESET = 0; RED = 31; GREEN; YELLOW; BLUE; MAGENTA; CYAN; GRAY }
function CCs() { [enum]::GetValues([CC]) | select -skip 1 | % { [pscustomobject]@{ Code = +$_; Name = (f $_ "$_") } } }
function Get-ColoredString($color, [string] $text) {
if ($Host.UI.SupportsVirtualTerminal) {
[char] $ESC = 27
[int] $code = $color -as [CC]
"$ESC[${code}m" + $text + "$ESC[0m"
} else {
$text
}
}
Set-Alias f Get-ColoredString
function Get-CalculatedProperty() {
param(
[object] $propname,
[string] $as = ($propname -creplace '(?<=[a-z])(?=[A-Z])', ' '),
[string] $format = "", [CC] $color = 0,
[switch] $left, [switch] $centered, [switch] $right
)
# Bail out if nothing is passed
if ($propname -eq $null) {
return @{}
}
# If the string passed to our "-As" flag ("$as" parameter) is convertible
# to a color code (our "[CC]" enum), use it in place of $color
if ($as -as [CC]) {
$color = $as
$as = $propname
}
# If -Format/$format is convertible to [CC], use it in place of $color
if ($format -as [CC]) {
$color = $format
$format = ""
}
# $true if no code generation for a [scriptblock] is needed
[bool] $passPropnameAsIs = `
$propname -is [scriptblock] -or `
$propname -is [string] -and $color -eq 0
$calcProp = @{
Name = $as
Expression = $(
if ($passPropnameAsIs) {
$propname
} else {
[string] $script = $(
if ($propname -is [string]) {
'$_.' + $propname
} else {
'(' + $propname.ToString().Trim() + ')'
}
)
if (-not [string]::IsNullOrEmpty($format)) {
$script = "'{0:$format}' -f ($script)"
}
if ($color -ne 0) {
$script = "Get-ColoredString $color ($script)"
}
[scriptblock]::Create($script)
}
)
}
if ($passPropnameAsIs -and -not [string]::IsNullOrEmpty($format)) {
$calcProp['f'] = $format
}
if ($left) { $calcProp['a'] = 'l' }
if ($centered) { $calcProp['a'] = 'c' }
if ($right) { $calcProp['a'] = 'r' }
$calcProp
}
Set-Alias gcp Get-CalculatedProperty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment