3
我在动态构建一堆高级函数。我一直在使用New-PSScript,但它不允许我寻找所有的灵活性。PowerShell MetaProgramming - 生成高级函数
我读手册页,了解功能的高级参数,看到一些有关动态参数的帮助文章的结尾这给下面的示例代码
function Sample {
Param ([String]$Name, [String]$Path)
DynamicParam
{
if ($path -match "*HKLM*:")
{
$dynParam1 = new-object
System.Management.Automation.RuntimeDefinedParameter("dp1",
[Int32], $attributeCollection)
$attributes = new-object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = 'pset1'
$attributes.Mandatory = $false
$attributeCollection = new-object
-Type System.Collections.ObjectModel.Collection``1[System.Attribute]
$attributeCollection.Add($attributes)
$paramDictionary = new-object
System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("dp1", $dynParam1)
return $paramDictionary
} End if
}
}
我想知道如果我可以使用RuntimeDefinedParameter并收集属性以生成新的功能。
一些半伪代码可能看起来像这样。我想构建的两个关键函数是New-Parameter和Add-Parameter。
$attributes1 = @{Mandatory=$true;Position=0;ValueFromPipeline=$true}
$param1 = New-Paramater -name foo -attributes $attributes1
$attributes2 = @{Mandatory=$true;Position=1}
$param2 = New-Paramater -name bar -attributes $attributes2
cd function:
$function = new-item -name Get-FooBar -value {"there is a $foo in the $bar"}
Add-Parameter -function $function -paramater $param1,$param2
我完全吠叫错了树吗?如果还有其他方法可以做到这一点,我很乐于接受可能性。
我可以看到的唯一的事这里缺少的是一旦你添加了参数,你将如何处理它们?除非你能够修改这个函数,否则你的函数会迭代一组参数和值... – 2009-06-02 17:50:11
我不完全确定这个流程是如何工作的。我想我会先创建函数Definiton,然后将参数添加到函数中。 在我的假代码中,我创建了一个函数,其中使用了稍后将作为参数添加的变量。 – 2009-06-02 18:11:03