Вопрос

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

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top