[英]PowerShell MetaProgramming - Generating Advanced Functions
我正在寻找动态构建一堆高级功能。 我一直在使用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
我完全吠叫错了树吗? 如果还有其他方法可以做到这一点,我对各种可能性持开放态度。
为了动态创建函数,我创建了定义函数的字符串,并调用Invoke-Expression来编译它并将其添加到函数提供程序中。 在我看来,这比在对象模型上工作更强大。
$ f1 = @“function New-Motor(){”这是我的新电机“}”@
Invoke-Expression $ f1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.