gpt4 book ai didi

.net - Powershell 函数参数类型 System.ConsoleColor - 函数参数列表中缺少 ')'

转载 作者:行者123 更新时间:2023-12-02 23:27:27 28 4
gpt4 key购买 nike

我正在尝试在 powershell 中创建一个带有 2 个参数的 cmdlet 函数。我希望这两个参数之一是 ConsoleColor但 ISE 提示并说函数参数列表中缺少 ')'。但我找不到这个缺少的 )

这是我的功能:

function Log {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[string[]]$messages,

# If I remove the following parameter, everything works fine
[System.ConsoleColor]$color = Default # ISE Complains here before `=`
)

if (($messages -eq $null) -or ($messages.Length -eq 0)) {
$messages = @("")
}

foreach ($msg in $messages) {
Write-Host $msg -ForegroundColor $color
$msg | Out-File $logFile -Append
}
}

我不太擅长 powershell,所以这可能是一些我还不知道的愚蠢的事情。

最佳答案

这个问题已经在评论中指出了。您不能只指定名为 Default 的内容作为参数的默认值。

由于该枚举没有“默认”值,因此我建议采用不同的方法。

不要使用参数的默认值,然后使用条件 (bleh) 或 splatting ( super 酷)来处理这个:

有条件

function Log {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[string[]]$messages,

[System.ConsoleColor]$color
)

if (($messages -eq $null) -or ($messages.Length -eq 0)) {
$messages = @("")
}

foreach ($msg in $messages) {
if ($color) {
Write-Host $msg -ForegroundColor $color
} else {
Write-Host $msg
}
$msg | Out-File $logFile -Append
}
}

泼溅

function Log {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[string[]]$messages,

[System.ConsoleColor]$color
)

$params = @{}
if ($color) {
$params.ForegroundColor = $color
}

if (($messages -eq $null) -or ($messages.Length -eq 0)) {
$messages = @("")
}

foreach ($msg in $messages) {
Write-Host $msg @params

$msg | Out-File $logFile -Append
}
}

关于.net - Powershell 函数参数类型 System.ConsoleColor - 函数参数列表中缺少 ')',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54243172/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com