Get ValueFromRemainingArguments as an hashtable

前端 未结 4 1866
时光说笑
时光说笑 2020-12-10 07:23

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

How can I

4条回答
  •  执念已碎
    2020-12-10 08:18

    Updated per Ansgars comment.

    One possibility is to build the hash-table within the function. Here is an example:

    function MyFunction
    {
        [CmdletBinding()]
        param([parameter(ValueFromRemainingArguments=$true)] $allparams)
    
        process
        {
            $myhash = @{}
            for ($i = 0; $i -lt $allparams.count; $i+=2)
            {
                $myhash[($allparams[$i]-replace '^-+')] = $allparams[$i+1]
            }
        }
        end
        {
            $myhash
        }
    }
    

    We parse through the params in the parameters $allparams using a for loop, and retrieve the key/value pairs to form the hash table, then in the end block we display it.

    MyFunction -var1 10 -var2 30 -var3 hello
    
    Name                          Value                     
    ----                          -----                     
    var1                          10                        
    var3                          hello                     
    var2                          30 
    

提交回复
热议问题