获取 ValueFromRemainingArguments 作为哈希表 [英] Get ValueFromRemainingArguments as an hashtable
本文介绍了获取 ValueFromRemainingArguments 作为哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 [parameter(ValueFromRemainingArguments=$true)]
可以将传递给函数的所有剩余参数作为列表放入一个变量中.
Using [parameter(ValueFromRemainingArguments=$true)]
one can get all the remaining arguments passed to the function into a variable as a list.
如何将剩余参数作为哈希表类型获取,例如对于 Function -var1 value1 -var2 value2
之类的输入?
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:
- 简单值(单个项目)
- 数组值
- 空值(开关)
脚本:
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] = $null
} else {
#Value
$htvars[$lastvar] = $_
}
}
#Return hashtable
$htvars
}
testf -simplepar value1 -arraypar value2,value3 -switchpar
输出:
Name: Frode
Vars count: 5
Vars:
Name Value
---- -----
arraypar {value2, value3}
switchpar
simplepar value1
这篇关于获取 ValueFromRemainingArguments 作为哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文