Allow multiple parameter with the same name for PowerShell function using ValueFromRemainingArguments

  Kiến thức lập trình

I’m trying to create a small PowerShell wrapper for the github-cli to handle a few cases that I just kept repeating over and over.

This is what I have at the moment:

function Invoke-Gh {
    <#
    .Synopsis
    Wrapper function that deals with Powershell's peculiar error output when gh uses the error stream.
    
    .Example
    Invoke-Git ThrowError
    $LASTEXITCODE
    
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$false)]
        [switch]$slurp,

        [Parameter(Mandatory=$false)]
        [switch]$fromJson,

        [parameter(ValueFromRemainingArguments=$true)]
        [string[]]$Arguments
    )

    $output = & {
        [CmdletBinding()]
        param(
            [parameter(ValueFromRemainingArguments=$true)]
            [string[]]$InnerArgs
        )
        $sleep = 0
        do {
            $output = & gh $InnerArgs
            if ($sleep -gt 0) {
                Start-Sleep -Seconds $sleep 
            }
            $sleep += 5
        }
        while ($output -like "*GraphQL: was submitted too quickly*")

        if ($LASTEXITCODE -ne 0) {
            throw "Error executing gh command: $InnerArgs"
        }

        if ($slurp) {
            $output = $output | & jq -s
        }

        if ($fromJson) {
            $output = $output | ConvertFrom-Json
        }
        return $output
    } -ErrorAction SilentlyContinue -ErrorVariable fail @Arguments

    if ($fail) {
        $fail.Exception
    }
        
    return $output
}

And it works great for most of my existing invocations, except when I’m calling the GraphQL API, which often requires a couple of parameters like this:

&gh api graphql --paginate -F enterprise=$enterprise -f query='query($endCursor: String, $enterprise: String!) {
           enterprise(slug: $enterprise) {
             id,
             organizations(first: 100, after: $endCursor) {
               nodes
               {
                 login,
                 name
               },
               pageInfo {
                   hasNextPage
                   endCursor
               }
             }
           }
         }' --jq '.data.enterprise.organizations.nodes' 

If I replace & gh with invoke-gh here I get the following error:

Invoke-Gh: Cannot bind parameter because parameter 'f' is specified more than once. To provide multiple values to parameters that can accept multiple values, use the array syntax. For example, "-parameter value1,value2,value3".

Is there a way for me to let the Parameter Binder ignore this case and just pass the remaining arguments as array like I want it to?

LEAVE A COMMENT