我正在考虑动态构建一组高级函数。我一直在使用New-PSScript来实现这一点,但它并没有考虑到我正在寻找的所有灵活性。
我阅读了关于函数高级参数的手册页,并在帮助文章的末尾看到了一些关于动态参数的内容,其中给出了以下示例代码
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-21 19:53:08
为了动态创建函数,我创建了定义函数的字符串,并调用Invoke-Expression对其进行编译并将其添加到函数提供程序中。在我看来,这比在对象模型上工作更强大。
$f1 = @“函数新马达(){”这是我的新马达“} "@
调用表达式$f1
https://stackoverflow.com/questions/939817
复制相似问题