Question:
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
?
Answer:
There are multiple ways to achieve this. The following solution supports parameters with:
- Simple value (single item)
- Array value
- Null value (switch)
Script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function testf { param( $name = "Frode", [parameter(ValueFromRemainingArguments=$true)] $vars ) "Name: $name" "Vars count: $($vars.count)" "Vars:" #Convert vars to hashtable $htvars = @{} $vars | ForEach-Object { if($_ -match '^-') { #New parameter $lastvar = $_ -replace '^-' $htvars[$lastvar] = $true } else { #Value $htvars[$lastvar] = $_ } } #Return hashtable $htvars } testf -simplepar value1 -arraypar value2,value3 -switchpar |
Output:
1 2 3 4 5 6 7 8 9 10 |
Name: Frode Vars count: 5 Vars: Name Value ---- ----- arraypar {value2, value3} switchpar simplepar value1 |
Edit: Modified default value assigned to Hashtable keys: $htvars[$lastvar] = $true
. Using $true
as the default accounts for switch parameters and can make the resulting Hastable more “splattable”.