Powershell 2.0 - 从脚本块中提取参数

时间:2015-07-07 11:21:57

标签: powershell powershell-v2.0 powershell-v3.0

有没有办法从PS 2.0中的脚本块外部提取脚本块的参数列表?

说我们有

$scriptb = { PARAM($test) }

在Powershell 3.0中我们可以做到这一点

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

然而,Ast属性包含在powershel 3.0中,因此上述内容在PS 2.0中不起作用https://msdn.microsoft.com/en-us/library/System.Management.Automation.ScriptBlock_properties%28v=vs.85%29.aspx

你知道在PS 2.0中有这样做的方法吗?

3 个答案:

答案 0 :(得分:2)

也许这不是一个漂亮的解决方案,但它可以完成工作:

# 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

输出:

Key Value
--- -----
x   System.Management.Automation.ParameterMetadata
y   System.Management.Automation.ParameterMetadata

答案 1 :(得分:0)

这个怎么样?

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

答案 2 :(得分:0)

看起来我可以这样做

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()

它将返回System.Management.Automation.ParameterMetadata的列表 https://msdn.microsoft.com/en-us/library/system.management.automation.parametermetadata_members%28v=vs.85%29.aspx

我认为应该有更好的方法。在那之前,我将使用上述代码的变体。

相关问题