3
나는 고급 함수를 동적으로 빌드하고자합니다. 나는 이것을 위해 New-PSScript을 사용했지만, 내가 찾고있는 모든 유연성을 허용하지 않는다. PowerShell 메타 프로그래밍 - 고급 함수 생성
나는 기능에 대한 고급 매개 변수에 대한 매뉴얼 페이지를 읽고 난 RuntimeDefinedParameter를 사용할 수 있는지 궁금하고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
}
}
다음 샘플 코드를 제공하는 도움말 문서의 끝 부분에 동적 매개 변수에 대해 뭔가를 보았다 새로운 기능을 생성하기위한 속성 모음.
일부 준 의사 코드는 다음과 같이 보일 수 있습니다. 내가 생각하고자하는 두 가지 주요 기능은 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
나는 완전히 잘못된 나무를 짖고 있습니까? 이것을 할 수있는 다른 방법이 있다면 나는 가능성에 대해 넓게 열려 있습니다.
내가 볼 수있는 유일한 여기서 누락되었습니다. 일단 매개 변수를 추가하면 매개 변수를 어떻게 할 것입니까? 함수를 수정할 수 없거나 매개 변수 및 값 컬렉션을 통해 함수를 반복하는 경우가 아니면 ... –
흐름이 어떻게 작동하는지 완전히 확신하지 못합니다. 나는 먼저 함수 정의를 만들고 함수에 매개 변수를 추가한다고 생각했습니다. 위조 코드에서는 매개 변수로 나중에 첨부 할 변수를 사용하는 값으로 함수를 만들었습니다. –