0

I'm attempting to add color to characters in a string using Write-Host in a subexpression, but it only outputs to the beginning of the string.

For example:

"This is $(Write-Host 'failing to work' -ForegroundColor Yellow -NoNewline)"

Outputs:

failing to workThis is

My goal is to make it easily reusable with something like:

function color {
    Write-Host $Args -ForegroundColor Yellow -NoNewline
}
"Add $(color 'to') strings"

EDIT

Thanks, lots of options there, but I don't see an explanation as to why $(Write-Host) behaves this way.

Community
  • 1
  • 1
Mica
  • 383
  • 3
  • 14
  • 1
    You are getting this behavior because Powershell is evaluating the sub-expression $() first before it can evaluate the string expression "This is..." – Bob M Sep 30 '16 at 01:34
  • Other cmdlets work as expected here. For example: `"Today is $((Get-Date).DayOfWeek)"` . How is Write-Host different? – Mica Sep 30 '16 at 02:51
  • 1
    If you look at the documentation for Write-Host, you'll note that its output is None. That's because it doesn't have a return a value, it writes directly to the host screen. Out-Host will also have a similar effect. – Bob M Sep 30 '16 at 03:32
  • I've rephrased the question because it really ought to be answered somewhere other than in a question marked closed/duplicate: http://stackoverflow.com/questions/39802919/why-does-a-subexpression-of-write-host-output-to-beginning-of-string – Mica Oct 01 '16 at 04:11

0 Answers0