Search code examples
powershell

Get ValueFromRemainingArguments as an hashtable


Using [parameter(ValueFromRemainingArguments=$true)] one can get all the remaining arguments passed to the function into a variable as a list.

How can I get the remaining arguments as a hashtable type, for example for inputs like Function -var1 value1 -var2 value2?


Solution

  • There are multiple ways to achieve this. The following solution supports parameters with:

    • Simple value (single item)
    • Array value
    • Null value (switch)
    • Colon syntax

    Script:

    function Get-Demo {
        param(
            $name = 'Frode',
            [parameter(ValueFromRemainingArguments = $true)]
            $vars
        )
    
        "Name: $name"
        "Vars count: $($vars.count)"
        'Htvars:'
    
        #Convert vars to ordered dictionary
        $htvars = [ordered]@{}
        $vars | ForEach-Object {
            if ($_ -match '^-(?<param>[^:]+):?$') {
                #New parameter
                $lastvar = $matches['param']
                $htvars[$lastvar] = $true # Default value for switch
            } else {
                # Update value to next argument
                $htvars[$lastvar] = $_
            }
        }
    
        #Return hashtable
        $htvars
    
    }
    
    Get-Demo -simplepar value1 -arraypar value2, value3  -colonParam:'hello world' -scriptblockParam { 'demo' } -switchpar -switchpar2:$false
    

    Output:

    Name: Frode
    Vars count: 11
    Htvars:
    
    Name                           Value
    ----                           -----
    simplepar                      value1
    arraypar                       {value2, value3}
    colonParam                     hello world
    scriptblockParam                'demo'
    switchpar                      True
    switchpar2                     False