PowerShell change color of output

The condition does not work, always "else"

Get-Process| Select-Object Name,VM | 
ForEach { 
if ($_.Name -eq "chrome") { [console]::ForegroundColor="red"; $_; } 
else { [console]::ForegroundColor="white"; $_; }  
[console]::ForegroundColor="white"; }

Upvotes: 0

Views: 1213

Answers (1)

FoxDeploy
FoxDeploy

Reputation: 13567

Use Write-Host instead, running [console]::ForegroundColor changes the color of all foreground text, basically all text that's not Verbose or Error Stream. However, you can change each line if you use Write-Host instead.

Get-Process msedge,notepad++,chrome | Select-Object Name | 
ForEach { 
    if ($_.Name -eq "chrome") { 
    write-host -ForegroundColor red $_.Name
        } 
    elseif ($_.Name -eq "msedge"){ 
    write-host -ForegroundColor green $_.Name; 
    }
    else{
    write-host -ForegroundColor white $_.Name; 
    }

}

And the output:

enter image description here

Upvotes: 1

Related Questions