Search code examples
functionpowershellparameterscolorswrite-host

Function with String Message, echos to screen, change the color of message


Good Morning all, SOLVED Both responses worked hand in hand. Big Thanks to Scepticalist and Wasif Hasan for the examples!!

I have a logging function that has a message parameter. Through the function it writes the message with a text color of green. Is there a way to change that color for certain messages for the log? Below is the function.

Function Get-Logger { 
    param(
       [Parameter(Mandatory=$True)]
       [String]$message
    )

    $TimeStamp = Get-Date -Format "MM-dd-yyy hh:mm:ss"

    Write-Host $TimeStamp -NoNewline
    Write-Host `t $message -ForegroundColor Green
    $logMessage = "[$TimeStamp]  $message"
    $logMessage | Out-File -Append -LiteralPath $VerboseLogFile
}

For example as the log function is called it echo's back the message as green text, which is fine. But if I wanted to use the logging function to change the text of section headers to yellow is there a way to do that? Below is what I'm kind of talking about

Get-Logger "Hello Word Starting" -Foregroundcolor yellow -nonewline

Solution

  • Like this?

    Function Get-Logger { 
        param(
           [Parameter(Mandatory=$True)][String]$message,
           [validatescript({[enum]::getvalues([system.consolecolor]) -contains $_})][string]$messagecolor,
           [switch]$nonewline
        )
    
        $TimeStamp = Get-Date -Format "MM-dd-yyy hh:mm:ss"
        If ($nonewline){
            Write-Host `t $message -ForegroundColor $($messagecolor) -nonewline
        }
        Else {
            Write-Host `t $message -ForegroundColor $($messagecolor)
        }
        $logMessage = "[$TimeStamp]  $message"
        $logMessage | Out-File -Append -LiteralPath $VerboseLogFile
    }
    

    Then:

    Get-Logger "Hello Word Starting" -messagecolour yellow -nonewline