Powershell 2.0 - 从脚本块中提取参数
Powershell 2.0 - extract parameters from script block
在 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 中执行此操作的方法吗?
这个呢?
$Scriptb = {
PARAM($test,$new)
return $PSBoundParameters
}
&$Scriptb "hello" "Hello2"
也许这不是一个很好的解决方案,但它完成了工作:
# 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
看来我可以做到这一点
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()
它将 return 列表 System.Management.Automation.ParameterMetadata
https://msdn.microsoft.com/en-us/library/system.management.automation.parametermetadata_members%28v=vs.85%29.aspx
我觉得应该有更好的办法。在那之前,我将使用上述代码的变体。
在 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 中执行此操作的方法吗?
这个呢?
$Scriptb = {
PARAM($test,$new)
return $PSBoundParameters
}
&$Scriptb "hello" "Hello2"
也许这不是一个很好的解决方案,但它完成了工作:
# 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
看来我可以做到这一点
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()
它将 return 列表 System.Management.Automation.ParameterMetadata https://msdn.microsoft.com/en-us/library/system.management.automation.parametermetadata_members%28v=vs.85%29.aspx
我觉得应该有更好的办法。在那之前,我将使用上述代码的变体。