在函数已经创建之后,是否可以向函数参数添加验证属性



我发现了这种动态更新参数的验证集成员的方法。

让我做这样的事情:

Function MyFunction([ValidateSet("Placeholder")]$Param1) { "$Param1" }
Update-ValidateSet -Command (Get-Command MyFunction) -ParameterName "Param1" -NewSet @("red","green")

但是,是否有任何方法可以添加一个尚未存在的验证属性?具体来说,我有一组函数,它们将通过动态创建验证集而受益匪浅。然而,正如上面的链接所表明的,这是一次黑客攻击,可能会在未来中断。所以我不想放一个占位符ValidateSet,以防将来需要删除它。本质上,我想做这样的事情:

Function MyFunction($Param1) { "Param1" }
Add-ValidateSet -Command (Get-Command MyFunction) -ParameterName "Param1" -NewSet @("red", "green")

这样,如果它真的中断了,那么删除中断代码会更容易。但我一直没能让它发挥作用。我试过这样做:

$parameter = (Get-Command MyFunction).Parameters["P1"]
$set = "Red","Orange","Yellow","Green","Blue","Indigo","Violet"
$Attribute = new-object System.Management.Automation.ValidateSetAttribute $Set
$ValidValuesField = [System.Management.Automation.ValidateSetAttribute].GetField("validValues", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance)
$ValidValuesField.SetValue($Attribute, [string[]]$Set)
$parameter.Attributes.Add($Attribute)

但它不起作用。

(Get-Command MyFunction).Parameters["P1"].Attributes

显示ValidateSet已添加,但选项卡完成不起作用。将其与使用UpdateValidateSet函数的结果进行比较,似乎不同之处在于该属性也应显示在下

(Get-Command MyFunction).ParameterSets[0].Parameters[0].Attributes

然而,这是一个ReadOnlyCollection,所以我似乎无法将其添加到那里。我是不是找错树了?这样做不可能吗?

您可以使用动态参数来实现这一点。在命令窗口中键入命令时,将评估动态参数。

这来自about_Functions_Advanced_Parameters

function Get-Sample {
[CmdletBinding()]
Param ([String]$Name, [String]$Path)
DynamicParam
{
if ($path -match ".*HKLM.*:")
{
$attributes = new-object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Mandatory = $false
$attributeCollection = new-object `
-Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$dynParam1 = new-object `
-Type System.Management.Automation.RuntimeDefinedParameter("dp1", [Int32], $attributeCollection)
$paramDictionary = new-object `
-Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("dp1", $dynParam1)
return $paramDictionary
}
}

最新更新