Get ValueFromRemainingArguments as an hashtable

前端 未结 4 1870
时光说笑
时光说笑 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:06

    There are a number of caveats with this method but I just wanted to show that ConvertFrom-StringData could also be considered here.

    function Convert-StringToHashTable {
    
        param(
            [parameter(ValueFromRemainingArguments=$true)]
            [string]$string
        )
    
        $string -replace "(^| )-","`r`n" | ForEach-Object{$_ -replace "(\w+) (.*)",'$1=$2'} | ConvertFrom-StringData
    }
    
    Convert-StringToHashTable -var1-5 value1 -var2 "value2 or 3"
    

    Output from above would be

    Name                           Value                                                                                                                                        
    ----                           -----                                                                                                                                        
    var2                           value2 or 3                                                                                                                                      
    var1-5                         value1   
    

    We take the all the remaining arguments as a single string. Then we split the string on - that occur at the beginning of the line or after a space. ( This accounts for dashes in the middle of works like Ansgar mentioned in another answer). Then we convert the first space after the first word into an equal sign. That will make a string of key value pairs that ConvertFrom-StringData expects.

    Known Caveats

    1. This will not work if you try to send arrays like in Frode's answer. He can handle those.

提交回复
热议问题