1

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
Fitzgery
  • 113
  • 8

2 Answers2

2

You need to add another switch "NoNewLine". So add this in param block:

[switch]$nonewline

And in the function body, do:

If ($nonewline){
  Write-Host `t $message -ForegroundColor $($messagecolour) -nonewline
}
Else {
  Write-Host `t $message -ForegroundColor $($messagecolour)
}

You can now add a validatescript on param block to validate color:

[validatescript({[enum]::getvalues([system.consolecolor]) -contains $_})][string]$messagecolor

Thanks to @Scepticalist

programmer365
  • 12,641
  • 3
  • 7
  • 28
1

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
Scepticalist
  • 2,502
  • 1
  • 9
  • 18
  • That does work, I'm trying to get some more flexibility out of it so I don't have to identify the whole acceptable color range in the function. Also the `-nonewline` section still pulls up as an error – Fitzgery Mar 11 '20 at 14:44
  • You can pull the default colours from PS with code and then use them as a validate set - I think I have an example somewhere, but it's relatively complex for such a small function. If you want -nonewline optional then you'll have to add it as a parameter for the function and code for it. Edit: As Wasan shows below :) – Scepticalist Mar 11 '20 at 15:01