write-output using colour

I needed to migrate PS scripts from using write-host to write-output but wanted to keep colour

I found this block of code


function Write-ColorOutput($ForegroundColor)
{
# save the current color
$fc = $host.UI.RawUI.ForegroundColor

# set the new color
$host.UI.RawUI.ForegroundColor = $ForegroundColor

# output
if ($args) {
Write-Output $args
}
else {
$input | Write-Output
}

# restore the original color
$host.UI.RawUI.ForegroundColor = $fc
}

# test
Write-ColorOutput red (ls)
Write-ColorOutput green (ls)
ls | Write-ColorOutput yellow

Leave a Reply

Your email address will not be published. Required fields are marked *