【问题标题】:Powershell function parameter type System.ConsoleColor - Missing ')' in function parameter listPowershell 函数参数类型 System.ConsoleColor - 函数参数列表中缺少“)”
【发布时间】:2019-01-17 19:40:56
【问题描述】:

我正在尝试在具有 2 个参数的 powershell 中创建一个 cmdlet 函数。我希望这两个参数之一是ConsoleColor,但 ISE 抱怨并说函数参数列表中有一个 Missing ')'。 但我找不到这个缺失的 )

这是我的功能:

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 方面不是很好,所以它可能是一些我还不知道的愚蠢的东西。

【问题讨论】:

  • 在此上下文中分配给 $color 的默认值是什么?它似乎不是有效的 System.ConsoleColor 标识符,所以我对它的来源很感兴趣。
  • default 是 PowerShell 语言关键字,仅在 switch 语句中有效。 PowerShell 不知道 C# default 关键字,也没有类似的概念。
  • ????我知道这很愚蠢......谢谢

标签: .net function powershell powershell-cmdlet


【解决方案1】:

问题已在 cmets 中指出。您不能只将名为 Default 的东西指定为参数的默认值。

由于该枚举没有“默认”值,我将建议一种不同的方法。

不要对参数使用默认值,然后使用条件 (bleh) 或 splatting(超级酷)来处理:

有条件的

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多