12

I have a function to write an output log to file and to console. The Write-Host part I'd like to color up a bit ;-)

switch($logLevel)
{
   "FATAL" { $ConsoleWriteColor = "blue"; break }
   "ERROR" { $ConsoleWriteColor = "red"; break }
   "WARN" { $ConsoleWriteColor = "yellow"; break }
   default { $ConsoleWriteColor = "white"; break }

}
Write-Host -ForegroundColor $ConsoleWriteColor "Hello world"

So my question is for the default case: How can I get the current foreground color? I guess it will not always be white?!

silent
  • 14,494
  • 4
  • 46
  • 86

2 Answers2

20

Current foreground and background can be obtained like this.

PS>(get-host).ui.rawui.ForegroundColor
Gray
PS>(get-host).ui.rawui.BackgroundColor
Black
hysh_00
  • 819
  • 6
  • 12
  • 1
    This always returns -1 for me?! – silent Oct 27 '14 at 07:50
  • 1
    @silent You are in PowerShell ISE correct? This command will work in the native shell. Try it there – Matt Oct 27 '14 at 11:29
  • 2
    Yeah you are right... there is does work, but it says DarkYellow when the text is clearly in white?! – silent Oct 27 '14 at 12:47
  • Looks like DarkYellow is missnamed. It is discussed here. http://stackoverflow.com/questions/21941606/why-does-powershell-display-darkyellow-text-improperly – hysh_00 Oct 28 '14 at 02:17
  • Oh dear :) thanks, so I guess the answer is ok after all – silent Oct 28 '14 at 12:57
  • 4
    When I run this in the Powershell ISE (v5.1.14409.1012), it returns `-1`, which does not cast to a `[System.ConsoleColor]`. That means that this would fail: `Write-Host -ForegroundColor ([System.ConsoleColor]-1) "Hello world"` – CJBS May 24 '18 at 18:26
1

To retrieve the foreground color in PowerShell, I found this command to work:

[System.Console]::ForegroundColor

Tested on:

  • Win 7: ISE and native shell
  • Win 10: ISE and native shell
  • Win 11: ISE, native shell and terminal

(Edited for clarity)

Jay_Nitzel
  • 11
  • 4
  • [ForegroundColor methods no longer effective in PowerShell v7.2.6 #17886](https://github.com/PowerShell/PowerShell/issues/17886) – joharr Aug 12 '22 at 19:54
  • 1
    @joharr I believe the point of the question was getting the current value, not setting it. as far as I can tell from what I have tested that functionality still works. – Jay_Nitzel Aug 16 '22 at 06:16