Foregroundcolor is not being set correctly inside ScriptBlock

170 views Asked by At

Edit: The issue I'm facing is from an ADO pipeline I have a ps1 script that does parallel execution. I want to set the foreground color to green but the code is not working when I am setting it inside the ScriptBlock

$color=[System.ConsoleColor]"Green"
$MainScriptblock = {
    Param($Repo,$CloningPath,$GitURL,$SourceBranch,$DestinationBranch,$ReleaseTag,$modulepath,$color)       
Write-Host "*****************************************************************" -ForegroundColor $color

}

foreach ($Repository in $ReposToBranch) {           
$job = Start-Job -Name $Repository -InitializationScript $InitScriptblock -ScriptBlock $MainScriptblock -ArgumentList $Repository,$Global:CloningPath,$GitURL, $SourceBranch, $DestinationBranch,$ReleaseTag,$modulepath,$color;
}

I tried using Microsoft.PowerShell.Utility\Write-Host but made no difference
I came across this post and the implementation is similar to mine. How to use a variable ForegroundColor with write-host onto Start-job

What could be wrong with my approach

1

There are 1 answers

0
mklement0 On

The problem:

Your issue isn't related to jobs, it is related to use of PowerShell in a CI/CD environment (an Azure DevOps pipeline in your case) or, more generally, when calling the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+) and capturing its output.

In that case, all output is invariably stringified, during which the coloring of Write-Host is currently (as of PowerShell (Core) 7.3.x) invariably lost.

A simple way to illustrate the problem from inside PowerShell:

# Due to capturing the output (piping to another command), the
# coloring is lost.
powershell.exe -c 'Write-Host -ForegroundColor Green green!' | Write-Output

GitHub issue #20171 suggests preserving the coloring, which would necessitate automatically embedding ANSI/VT escape sequences that correspond to the -Foreground / -Background arguments in the output text, as shown manually below.


Workaround:

As Santiago notes, you'll have to embed the ANSI/VT escape sequences yourself, instead of using the -ForegroundColor / -BackgroundColor parameters of Write-Host:

In Windows PowerShell:

Write-Host "$([char] 27)[32m******$([char] 27)[m"

In PowerShell (Core) 7+, you can more conveniently use the $PSStyle preference variable:

# PS v7.2+ only
Write-Host "$($PSStyle.Foreground.Green)******$($PSStyle.Reset)"