Domanda

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 ...}

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top