假设您具有以下功能:
Function Test-Function {
Param (
[String[]]$ComputerNames = @($env:COMPUTERNAME, 'PC2'),
[String]$PaperSize = 'A4'
)
}
Get-DefaultParameterValuesHC -Path 'Test-Function'
现在,要获取函数参数中的默认值,可以使用AST:
Function Get-DefaultParameterValuesHC {
[OutputType([hashtable])]
Param (
[Parameter(Mandatory)]$Path
)
$ast = (Get-Command $Path).ScriptBlock.Ast
$selectParams = @{
Property = @{
Name = 'Name';
Expression = { $_.Name.VariablePath.UserPath }
},
@{
Name = 'Value';
Expression = { $_.DefaultValue.Extent.Text -replace "`"|'" }
}
}
$result = @{ }
$defaultValueParameters = @($ast.FindAll( {
$args[0] -is [System.Management.Automation.Language.ParameterAst] }
, $true) |
Where-Object { $_.DefaultValue } |
Select-Object @selectParams)
foreach ($d in $defaultValueParameters) {
$result[$d.Name] = foreach ($value in $d.Value) {
$ExecutionContext.InvokeCommand.ExpandString($value)
}
}
$result
}
这里的问题是for的参数$ComputerNames
被读了一段string
时间,实际上它是一个数组string
。
PowerShell是否可以将字符串转换为数组?甚至更好的是,首先正确读取值?
您需要更深入地研究AST结构...
我建议您使用此PowerShell:AST Explorer GUI:
对于您的特定示例:
Function Test-Function {
Param (
[String[]]$ComputerNames = @($env:COMPUTERNAME, 'PC2'),
[String]$PaperSize = 'A4'
)
}
$FunctionDefinitionAst = (Get-Command 'Test-Function').ScriptBlock.Ast
$Body = $FunctionDefinitionAst.Body
$ParamBlock = $Body.ParamBlock
$CNParameter = $ParamBlock.Parameters | Where-Object { $_.Name.VariablePath.UserPath -eq 'ComputerNames' }
$DefaultValue = $CNParameter.DefaultValue
$DefaultValue.SubExpression.Statements.PipelineElements.Expression.Elements
VariablePath : env:COMPUTERNAME
Splatted : False
StaticType : System.Object
Extent : $env:COMPUTERNAME
Parent : $env:COMPUTERNAME, 'PC2'
StringConstantType : SingleQuoted
Value : PC2
StaticType : System.String
Extent : 'PC2'
Parent : $env:COMPUTERNAME, 'PC2'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句