0

I am trying to run .NET locally. When I use dotnet watch run command and when I do something in Swagger UI I get a lot of output text in the PowerShell console. I want to color words as info and error when I use them and when they appear in the output.

I tried using PowerShell profile. This is where I ended up but it is not working.

function coloredText{
    $output = Invoke-Expression $input
    
    foreach ($line in $output) {
        $coloredLine = $line -replace 'info', "$(Write-Color -Text 'info' -ForegroundColor Blue)"
        Write-Host $coloredLine
    }
}

# Define an alias for the command to be execute with the function
Set-Alias -Name "dotnet watch run" -Value "dotnet watch run | coloredText"

# Call Out-Default to execute the function on every change in the output
Out-Default 
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Light
  • 1
  • 1

1 Answers1

0

There are some difficult ways to do this and an easy, but hacky way.

ANSI escape sequences can be embedded into a string to set colors for a console that recognizes them.

You could also parse the line into tokens and write each part with a separate Write-Host command, colorized if the part = 'info'.

The easy way is to replace 'info' with a Write-Host command and use Invoke-Expression to execute it:

$OutputLines = @"
This is a line without the keyword
This is a line with info in it and '
This is a line with info in it more than once. info and info
"@ -split "`n" #this must be an array 
foreach($line in $OutputLines){
    Invoke-Expression ("Write-Host -NoNewLine '" + 
    $line.Replace('''',''''''). #you can leave off this Replace if your output doesn't contain '
    Replace('info',"';Write-Host -NoNewLine -ForegroundColor Blue 'info';Write-Host -NoNewLine '") + 
    "'; Write-Host ''") #add a newline to the end
}
Rich Moss
  • 2,195
  • 1
  • 13
  • 18