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
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.exefor Windows PowerShell,pwshfor PowerShell (Core) 7+) and capturing its output.In that case, all output is invariably stringified, during which the coloring of
Write-Hostis currently (as of PowerShell (Core) 7.3.x) invariably lost.A simple way to illustrate the problem from inside PowerShell:
GitHub issue #20171 suggests preserving the coloring, which would necessitate automatically embedding ANSI/VT escape sequences that correspond to the
-Foreground/-Backgroundarguments 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/-BackgroundColorparameters ofWrite-Host:In Windows PowerShell:
In PowerShell (Core) 7+, you can more conveniently use the
$PSStylepreference variable: