PowerShell cmdlet参数值选项卡完成

Dav*_*ner 12 powershell powershell-3.0

如何在PowerShell 3.0中实现PowerShell函数或cmdlet(如Get-Service和Get-Process)的参数选项卡完成?

我意识到ValidateSet适用于已知列表,但我想按需生成列表.

Adam Driscoll 暗示说 cmdlet 是可能的,但遗憾的是还没有详细说明.

Trevor Sullivan 展示了一种函数技术,但据我所知,他的代码只在定义函数时生成列表.

Mar*_*cus 7

我困惑了一段时间,因为我想做同样的事情.我把我真正满意的东西放在一起.

您可以从DynamicParam添加ValidateSet属性.这是我从xml文件中即时生成ValidateSet的示例.请参阅以下代码中的"ValidateSetAttribute":

function Foo() {
    [CmdletBinding()]
    Param ()
    DynamicParam {
        #
        # The "modules" param
        #
        $modulesAttributeCollection = new-object -Type System.Collections.ObjectModel.Collection[System.Attribute]

        # [parameter(mandatory=...,
        #     ...
        # )]
        $modulesParameterAttribute = new-object System.Management.Automation.ParameterAttribute
        $modulesParameterAttribute.Mandatory = $true
        $modulesParameterAttribute.HelpMessage = "Enter one or more module names, separated by commas"
        $modulesAttributeCollection.Add($modulesParameterAttribute)    

        # [ValidateSet[(...)]
        $moduleNames = @()
        foreach($moduleXmlInfo in Select-Xml -Path "C:\Path\to\my\xmlFile.xml" -XPath "//enlistment[@name=""wp""]/module") {
            $moduleNames += $moduleXmlInfo.Node.Attributes["name"].Value
        }
        $modulesValidateSetAttribute = New-Object -type System.Management.Automation.ValidateSetAttribute($moduleNames)
        $modulesAttributeCollection.Add($modulesValidateSetAttribute)

        # Remaining boilerplate
        $modulesRuntimeDefinedParam = new-object -Type System.Management.Automation.RuntimeDefinedParameter("modules", [String[]], $modulesAttributeCollection)

        $paramDictionary = new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
        $paramDictionary.Add("modules", $modulesRuntimeDefinedParam)
        return $paramDictionary
    }
    process {
        # Do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

有了它,我可以输入

Foo -modules M<press tab>
Run Code Online (Sandbox Code Playgroud)

如果该模块在XML文件中,它将选项卡完成"MarcusModule".此外,我可以编辑XML文件,并且tab-completion行为将立即改变; 您不必重新导入该功能.


Sha*_*evy 4

查看 github 上的 TabExpansionPlusPlus 模块,由前 PowerShell 团队魔术师编写。

https://github.com/lzybkr/TabExpansionPlusPlus#readme