Powershell 2.0 - Retrieves parameters from script block

Is there a way to extract a list of script block parameters from outside the script block in PS 2.0?

Let's say that

$scriptb = { PARAM($test) }

      

In Powershell 3.0 we can do this

$scriptb.Ast.ParamBlock.Parameters.Count == 1 #true

      

However the Ast property was included in powershel 3.0, so the above won't 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 how to do this in PS 2.0?

+3


source to share


3 answers


It might not be 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

      

+1


source


How about this?



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

      

0


source


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 must be a better way. Until then, I will use a variation of the above code.

0


source







All Articles