4

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 ?

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. Thank you for this, your code looks better. I will give it a try.
0

What about this?

$Scriptb = {
PARAM($test,$new)
return $PSBoundParameters
}
&$Scriptb "hello" "Hello2"

1 Comment

Thank you. However that will not return all the information from the parameter as scriptb.Ast.ParamBlock.Parameters from PS 3.0 does. (Attribute decorations for instance)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.