1

If it helps, I'm on PowerShell Core, v.6.0.1 or v.6.1.0. Apparently, on some versions of PowerShell the parsing of -1 results in an error, but not on either of my systems. In fact, I can get a "valid" ConsoleColor given any negative number. I'm just trying to understand why that works, and what it means.


I'm playing with a PowerShell script that lets you select from a menu of options using arrow keys: here, discussed in this question.

I notice that the script's code tries to use the current values of [Console]::BackgroundColor and [Console]::ForegroundColor, but in my PowerShell session, those values are returned as -1, which is not a value that can be used to set them.

I changed the script to override the values with some colors of my choice if they're not already customized, but then I wanted to also be able to reset them. [Console]::ResetColor() resets both the background and the foreground colors, so I can't use it if one of them is customized while the other is not.

However, this does work:

[Console]::ForegroundColor = [Enum]::Parse([ConsoleColor], -1)

I actually found that I could back up the original colors and assign them back with no issues, so now I'm just wondering about the behavior of this enum in general.

Why does the above work but not [Console]::ForegroundColor = -1?

Tatiana Racheva
  • 1,289
  • 1
  • 13
  • 31

1 Answers1

1

I curious what you are after.

To document an enum use :

[Enum]::GetValues([ConsoleColor]) | Select-Object @{n="Name";e={"$_"}},value__

Sample output:

Name        value__
----        -------
Black             0
DarkBlue          1
DarkGreen         2
DarkCyan          3
DarkRed           4
DarkMagenta       5
DarkYellow        6
Gray              7
DarkGray          8
Blue              9
Green            10
Cyan             11
Red              12
Magenta          13
Yellow           14
White            15

Your above code results in an error here with PSv6.1

[Console]::ForegroundColor = [Enum]::Parse([ConsoleColor], -1)

Exception setting "ForegroundColor": "The ConsoleColor enum value was not defined on that enum. Please use a defined color from the enum." At line:1 char:1 + [Console]::ForegroundColor = [Enum]::Parse([ConsoleColor], -1) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException + FullyQualifiedErrorId : ExceptionWhenSetting

To backup a color

$OldForegroundColor = $Host.UI.RawUI.ForeGroundColor
  • What can I say, I don't see an error, and that line works on both my Mac (6.0.2) and my Linux machine (6.1.0). – Tatiana Racheva Oct 29 '18 at 21:18
  • FWIW, I see the same enum values as you list here, except that parsing -1 does work, and I can, in fact, assign it to ForegroundColor or BackgroundColor (which resets that specific color setting, which is what I was after in the first place). – Tatiana Racheva Oct 29 '18 at 21:20