Reputation:
Is there a way to extract the parameter list of a script block from outside the script block in PS 2.0 ?
Say we have
$scriptb = { PARAM($test) }
In Powershell 3.0 we can do this
$scriptb.Ast.ParamBlock.Parameters.Count == 1 #true
The Ast property however was included in powershel 3.0 so the above will not work in PS 2.0 https://msdn.microsoft.com/en-us/library/System.Management.Automation.ScriptBlock_properties%28v=vs.85%29.aspx
Do you know of a way to do this in PS 2.0 ?
Upvotes: 4
Views: 634
Reputation:
It looks like I can do this
function Extract {
PARAM([ScriptBlock] $sb)
$sbContent = $sb.ToString()
Invoke-Expression "function ____ { $sbContent }"
$method = dir Function:\____
return $method.Parameters
}
$script = { PARAM($test1, $test2, $test3) }
$scriptParameters = Extract $script
Write-Host $scriptParameters['test1'].GetType()
It will return a list of System.Management.Automation.ParameterMetadata https://msdn.microsoft.com/en-us/library/system.management.automation.parametermetadata_members%28v=vs.85%29.aspx
I think there should be a better way. Until then I will use a variation of the above code.
Upvotes: 0
Reputation: 8889
What about this?
$Scriptb = {
PARAM($test,$new)
return $PSBoundParameters
}
&$Scriptb "hello" "Hello2"
Upvotes: 0
Reputation: 42033
Perhaps it is not a pretty solution but it gets the job done:
# some script block
$sb = {
param($x, $y)
}
# make a function with the scriptblock
$function:GetParameters = $sb
# get parameters of the function
(Get-Command GetParameters -Type Function).Parameters
Output:
Key Value
--- -----
x System.Management.Automation.ParameterMetadata
y System.Management.Automation.ParameterMetadata
Upvotes: 1