简体   繁体   English

带字符串消息的函数,回显到屏幕,改变消息的颜色

[英]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!!非常感谢怀疑论者和 Wasif Hasan 的例子!!

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.例如,当调用 log 函数时,它会将消息作为绿色文本回显,这很好。 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

You need to add another switch "NoNewLine".您需要添加另一个开关“NoNewLine”。 So add this in param block:所以在 param 块中添加这个:

[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:您现在可以在 param 块上添加一个验证脚本来验证颜色:

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

Thanks to @Scepticalist感谢@Scepticalist

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM