Abr*_*ala 5 powershell powershell-5.1
试图更好地理解动态参数,但有些事情一直困扰着我。我在外部网络(互联网)上找到的所有示例,参数属性总是被定义/包含的。
这是我正在处理的内容:
Function Test-DynamicParameters {
[cmdletbinding()]
Param (
[System.IO.DirectoryInfo]$Path
)
DynamicParam
{
if ($Path.Extension) {
$parameterAttribute = [System.Management.Automation.ParameterAttribute]@{
Mandatory = $false
}
$attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
$attributeCollection.Add($parameterAttribute)
$dynParam1 = [System.Management.Automation.RuntimeDefinedParameter]::new(
'TestSwitch', [switch], $attributeCollection
)
$paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$paramDictionary.Add('TestSwitch', $dynParam1)
$paramDictionary
}
}
Begin { }
Process
{
$PSBoundParameters
}
End { }
}
Run Code Online (Sandbox Code Playgroud)
。。目前已经尝试了多种删除某些行/代码的组合,以查看什么会使我的动态参数显示,但如果没有声明属性,则任何操作都不起作用。有这个必要吗?
问题:要使其正常工作,动态参数声明的最简单形式是什么?
例如 - 它可以缩短为我只定义名称吗?或者,PowerShell 会坚持指定类型而不是默认类型吗[object]?就像是:
$paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$paramDictionary.Add('TestSwitch')
$paramDictionary
Run Code Online (Sandbox Code Playgroud)
您正在寻找什么样的行为?因为即使自动完成是动态的,通常也不需要动态参数。
例如你可以这样做
Get-Command -Module您可以在 WindowsPowershell 中使用DynamicValidateSet模式

新:[IValidateSetValuesGenerator]和[ArgumentCompletions]
它会像 一样自动完成[ValidateSet],但用户仍然可以自由输入其他内容。
注意,[ArgumentCompletions]和[ArgumentCompleter]是两个不同的类。
[Parameter(Mandatory)]
[ArgumentCompletions('Fruits', 'Vegetables')]
[string]$Type,
Run Code Online (Sandbox Code Playgroud)
带有接口的新[ArgumentCompleter]属性[IArgumentCompleterFactory]
来自文档:
[DirectoryCompleter(ContainingFile="pswh.exe", Depth=2)]
[DateCompleter(WeekDay='Monday', From="LastYear")]
[GitCommits(Branch='release')]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |