让我们谈谈为什么它不起作用
function Test()
param(
[Parameter(Mandatory=$false, Position=0)]
[ValidateSet('Controllers','test2','test3')]
[String]$options
)
}
参数是在脚本开始时创建并填写的变量
ValidateSet 仅在 $Options 等于 'Controllers','test2','test3' 三个选项之一时才允许脚本运行
让我们谈谈[] 到底在做什么
Mandatory=$false 表示 $options 不必是任何东西才能运行脚本。
Position=0 表示如果您输入脚本时没有使用-options,那么您输入的第一件事仍然是选项
例子
#If Position=0 then this would work
Test "Controllers"
#Also this would work
Test -options Controllers
[ValidateSet('Controllers','test2','test3')] 表示如果使用 Option 或者是 Mandatory 那么它必须等于 'Controllers','test2','test3'
听起来您正在尝试在运行时创建参数。这可以使用DynamicParam。
function Test{
[CmdletBinding()]
param()
DynamicParam {
$Parameters = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
'Controllers','test2','test3' | Foreach-object{
$Param = New-Object System.Management.Automation.ParameterAttribute
$Param.Mandatory = $false
$AttribColl = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$AttribColl.Add($Param)
$RuntimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter("$_", [string], $AttribColl)
$Parameters.Add("$_", $RuntimeParam)
}
return $Parameters
}
begin{
$PSBoundParameters.GetEnumerator() | ForEach-Object{
Set-Variable $_.Key -Value $_.Value
}
}
process {
"$Controllers $Test2 $Test3"
}
}
DynamicParam 允许您在代码中创建参数。
上面的例子把数组'Controllers','test2','test3'变成了3个独立的参数。
Test -Controllers "Hello" -test2 "Hey" -test3 "Awesome"
返回
Hello Hey Awesome
但是你说要保留hypen和参数
所以这条线
$PSBoundParameters.GetEnumerator() | ForEach-Object{
Set-Variable $_.Key -Value $_.Value
}
允许您定义每个参数值。像这样的轻微变化:
$PSBoundParameters.GetEnumerator() | ForEach-Object{
Set-Variable $_.Key -Value "-$($_.Key) $($_.Value)"
}
会回来
-Controllers Hello -test2 Hey -test3 Awesome