动态参数的最简单形式是什么?

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)

nin*_*key 3

您正在寻找什么样的行为?因为即使自动完成是动态的,通常也不需要动态参数。

例如你可以这样做

  • 自动完成模块名称Get-Command -Module
  • 或按文件类型搜索文件,仅搜索该目录中存在的完整文件类型

Windows Powershell

您可以在 WindowsPowershell 中使用DynamicValidateSet模式

使用 DynamicValidateSet 的 gif

https://i.stack.imgur.com/nnLBS.gif

PowerShell 中的新功能

6 添加建议

新:[IValidateSetValuesGenerator][ArgumentCompletions]

它会像 一样自动完成[ValidateSet],但用户仍然可以自由输入其他内容。

注意,[ArgumentCompletions][ArgumentCompleter]是两个不同的类。

[Parameter(Mandatory)]
[ArgumentCompletions('Fruits', 'Vegetables')]
[string]$Type,
Run Code Online (Sandbox Code Playgroud)

7.2 通用完成器

带有接口的新[ArgumentCompleter]属性[IArgumentCompleterFactory]

来自文档:

[DirectoryCompleter(ContainingFile="pswh.exe", Depth=2)]

[DateCompleter(WeekDay='Monday', From="LastYear")]

[GitCommits(Branch='release')]
Run Code Online (Sandbox Code Playgroud)