1

大家早上好,已 解决 两个响应齐头并进。非常感谢 Scepticalist 和 Wasif Hasan 提供的示例!

我有一个带有消息参数的日志记录功能。通过该函数,它以绿色的文本颜色写入消息。有没有办法改变日志的某些消息的颜色?下面是函数。

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
}

例如,调用 log 函数时,它会将消息回显为绿色文本,这很好。但是,如果我想使用日志记录功能将部分标题的文本更改为黄色,有没有办法做到这一点?下面是我想说的

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

2 回答 2

2

您需要添加另一个开关“NoNewLine”。所以在参数块中添加这个:

[switch]$nonewline

在函数体中,执行:

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

您现在可以在 param 块上添加一个 validatescript 来验证颜色:

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

感谢@Scepticalist

于 2020-03-11T14:59:50.900 回答
1

像这样?

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
}

然后:

Get-Logger "Hello Word Starting" -messagecolour yellow -nonewline
于 2020-03-11T14:35:16.307 回答