문제

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