Question

I would like to print a number in green if it's 100 or red if less, but this is not working

Write-Host -ForegroundColor { (if ($number -eq 100) {Green} else {Red}) } "$number"

How can I do this without having

if (...) {Write-Host ...} else {Write-Host ...}

Was it helpful?

Solution

Try it like this:

Write-Host $number -ForegroundColor $(if ($number -eq 100) {'Green'} else {'Red'})

You don't want to use {} in this case. ForegroundColor does not accept a scriptblock and it is not pipeline bound. Besides you're not piping anything into Write-Host. A subexpression $() allows you to evaluate statements like if, foreach, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top