PowerShell元编程-生成高级函数
我正在研究动态构建一系列高级功能。我一直在使用它,但它不允许所有的灵活性,我正在寻找 我正在阅读有关函数和高级参数的手册页,在帮助文章的末尾看到了一些关于动态参数的内容,文章给出了以下示例代码PowerShell元编程-生成高级函数,powershell,metaprogramming,powershell-2.0,Powershell,Metaprogramming,Powershell 2.0,我正在研究动态构建一系列高级功能。我一直在使用它,但它不允许所有的灵活性,我正在寻找 我正在阅读有关函数和高级参数的手册页,在帮助文章的末尾看到了一些关于动态参数的内容,文章给出了以下示例代码 function Sample { Param ([String]$Name, [String]$Path) DynamicParam { if ($path -match "*HKLM*:") { $dynPara
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和属性集合来生成新函数
某些半伪代码可能如下所示。我试图构建的两个关键函数是newparameter和addparameter
$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
我完全找错人了吗?如果有其他方法可以实现这一点,我完全愿意接受各种可能性。为了动态创建函数,我创建了定义函数的字符串,并调用调用表达式来编译它并将其添加到函数提供程序中。在我看来,这比处理对象模型更强大 $f1=@” 新功能-电机() { “这是我的新马达” } "@
调用表达式$f1我能看到的唯一缺失是,一旦添加了参数,您将如何处理它们?除非您能够修改函数,或者您的函数通过参数和值的集合进行迭代……否则我不能完全确定流将如何工作。我想我应该先创建函数定义,然后将参数添加到函数中。在我的伪代码中,我创建了一个函数,该函数的值使用了我稍后附加的变量作为参数。