Changing the background and text colors of my PowerShell script that opens in a cmd window

Bray, Gary 0 Reputation points
2023-12-21T15:27:03.72+00:00

I have a simple PowerShell script that opens in a cmd window when I run it.

My question is how can I change the text color from "red" to white or yellow and the background color as well? I've tried going to "properties" in the cmd windows and changing the cmd window attributes, but my script still runs like the attached screenshot.

I've also tried adding this code to my script w/o any success:

Set console colors to black background and yellow text

$Host.UI.RawUI.BackgroundColor = "Black"

$Host.UI.RawUI.ForegroundColor = "Yellow"

Clear the screen to apply the new colors

Clear-Host

Your PowerShell script code goes here

Write-Host "Hello, this is a sample script."

Reset colors (optional)

$Host.UI.RawUI.ResetColor(

Thursday, December 21, 2023 9-35-01 AM

Thursday, December 21, 2023 9-18-39 AM

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2023-12-21T16:14:54.7633333+00:00

    PowerShells default handling of ErrorRecord objects uses red text. Changing the default colors in the shell won't change that because PowerShell changes the text color for that type of information.

    You can wrap your code in try/catch block(s) and save the ErrorRecord to a variable and then send the contents to the shell. That should use the shells default colors.

    I think you should be more concerned about the reason(s) your script is failing!


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.