'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 1:[1]

Here is how you can accomplish what you're trying to achieve.

$format1 = @{
    ForegroundColor = "White"
    BackgroundColor = "Black"
}

Write-Host "Example" @format1

This method is called Splatting and basically is how you can pass multiple arguments to a function using a hashtable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1