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
?
There are multiple ways to achieve this. The following solution supports parameters with:
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