powershellvariablestextcolorswrite-host

Variables that contains the color of a text in PowerShell


Is it possible to store in a variable the color of a text? I tried this but it doesn't work:

$format1 = "-ForegroundColor White"
$format2 = "-BackgroundColor Black"

Write-Host "Example" $format1 $format2

It returns:

"Example -ForegroundColor White -BackgroundColor Black" #(not colored)

Solution

  • You can use Splatting, basically this is method allows you to store the parameter names and values in a hash table and later on, use it to bind them to a command:

    $format1 = @{
        ForegroundColor = "White"
        BackgroundColor = "Black"
    }
    
    Write-Host "Example" @format1