如何以编程方式确定函数参数的默认值?
请考虑以下功能:
function f {param($x = 42)}
$ x
的默认值为42.假设我有一堆函数,它们的参数除其他外,我要通过编程方式对其默认值进行测试.通过使用以下命令之一返回的对象,我还能发现其他事情:
$x
has a default value of 42. Suppose I have a bunch of functions whose parameters I want to test programmatically for, among other things, their default values. Those other things I am able to discover using the objects returned using one of the following commands:
Get-Item function:/f | % Parameters | % x | % Attributes
Get-Help f | % Parameters | % parameter
这些命令输出以下内容:
Those commands output the following:
Position : 0
ParameterSetName : __AllParameterSets
Mandatory : False
ValueFromPipeline : False
ValueFromPipelineByPropertyName : False
ValueFromRemainingArguments : False
HelpMessage :
HelpMessageBaseName :
HelpMessageResourceId :
DontShow : False
TypeId : System.Management.Automation.ParameterAttribute
name : x
required : false
pipelineInput : false
isDynamic : false
parameterSetName : (All)
parameterValue : Object
type : @{name=Object}
position : 0
aliases : None
关于默认值似乎没有任何线索.
There doesn't seem to be any clue as to the default value.
如何以编程方式确定函数参数的默认值?
How can I programmatically determine the default value of a function parameter?
您可以使用语法树查找参数的默认值表达式.
You can use syntax tree to find default value expression for parameter.
function f {
param(
$x = 42,
$y = 6*7,
$z = (Get-Random)
)
}
$Parameters = (Get-Item function:\f).ScriptBlock.Ast.Body.ParamBlock.Parameters
$xDefaultValue = $($Parameters.Where{$_.Name.VariablePath.UserPath -eq 'x'}).DefaultValue
$yDefaultValue = $($Parameters.Where{$_.Name.VariablePath.UserPath -eq 'y'}).DefaultValue
$zDefaultValue = $($Parameters.Where{$_.Name.VariablePath.UserPath -eq 'z'}).DefaultValue
然后可以使用语法树节点的 SafeGetValue()
方法检索常量值,但不适用于表达式.
You can than use SafeGetValue()
method of syntax tree node to retrieve constant value, but it does not work with expressions.
$xDefaultValue.SafeGetValue()
$yDefaultValue.SafeGetValue()
$zDefaultValue.SafeGetValue()