0
votes

How can I colour in red only the variable $server?

Something like Add-Member Noteproperty -name Server -value (Write-Host $server -foregroundcolour red)

$object = New-Object PSObject
$object | Add-Member Noteproperty -name User -value $user
$object | Add-Member Noteproperty -name Server -value $server
$object |fl

Thanks

2

2 Answers

1
votes

Out of the box you cannot. Colouring, or -ForegroundColor and -BackgroundColor switches, are only available on Write-Host cmdlet.
You would have to write a custom function which processes values from $object and writes them to console using Write-Host.

1
votes

In case anyone wants to know, if your console supports VT (Virtual Terminal) escape sequences, you can use it directly.

The original post uses New-Object, which is considered the legacy approach. Therefore, in my example I will use the [PSCustomObject] type to convert an [ordered]hashtable.

For the VT colors, I referenced a StackExchange's SuperUser post I found.
Also, I add ESC[0m (in the form of $esc[0m) to the end of the VT command to reset the color.

# Grab some data to work with
# NOTE: This grabs either the domain name or Windows workgroup name
$domain = (Get-CimInstance -ClassName "Win32_ComputerSystem").Domain

$boolDomainJoined = (Get-CimInstance -ClassName "Win32_ComputerSystem").PartOfDomain

# VT (Virtual Terminal) escape sequences
$esc = [char]27
$grayDark = 90
$greenBright = 92
$redBright = 91

# New empty object
$objHT = [PSCustomObject][ordered]@{}

# Get fancy and even colorize the custom property name
$objHT | Add-Member -MemberType NoteProperty -Name "$esc[${grayDark}m$("Computer name")$esc[0m" -Value $env:COMPUTERNAME

# Check if computer is part of a domain
if ($boolDomainJoined) {
    $objHT | Add-Member -MemberType NoteProperty -Name "Domain" -Value "$esc[${greenBright}m$($domain)$esc[0m"
} else {
    $objHT | Add-Member -MemberType NoteProperty -Name "Workgroup" -Value "$esc[${redBright}m$($domain)$esc[0m"
}

# Display object as a list
$objHT | Format-List

Output: