PowerShell cmdlet参数值选项卡完成

时间:2013-02-13 00:38:27

标签: powershell powershell-v3.0

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

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

Adam Driscoll hints that it is possible关于cmdlet但遗憾的是还没有详细说明。

Trevor Sullivan shows a technique了解函数,但据我了解,他的代码只在定义函数时生成列表。

3 个答案:

答案 0 :(得分: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
    }
}

有了这个,我可以输入

Foo -modules M<press tab>

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

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

经典,我使用了正则表达式。

例如,

function TabExpansion {

    param($line, $lastWord) 

    if ( $line -match '(-(\w+))\s+([^-]*$)' )
    {
    ### Resolve Command name & parameter name
        $_param = $matches[2] + '*'
        $_opt = $Matches[3].Split(" ,")[-1] + '*'
        $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length)

        $_cmdlet = [regex]::Split($line, '[|;=]')[-1]

        if ($_cmdlet -match '\{([^\{\}]*)$')
        {
            $_cmdlet = $matches[1]
        }

        if ($_cmdlet -match '\(([^()]*)$')
        {
            $_cmdlet = $matches[1]
        }

        $_cmdlet = $_cmdlet.Trim().Split()[0]

        $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet)[0]

        while ($_cmdlet.CommandType -eq 'alias')
        {
            $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet.Definition)[0]
        }

    ### Currently target is Get-Alias & "-Name" parameter

        if ( "Get-Alias" -eq $_cmdlet.Name -and "Name" -like $_param )
        {
           Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\s','` ') }
           break;
        }
    }
}

参考 http://gallery.technet.microsoft.com/scriptcenter/005d8bc7-5163-4a25-ad0d-25cffa90faf5


Posh-git将TabExpansion重命名为GitTabExpansion.ps1中的TabExpansionBackup。
当完成与git命令不匹配时,posh-git的redifined TabExpansion调用原始TabExpansion(TabExpansionBackup)。
所以你要做的就是重新定义TabExpansionBackup。

(cat。\ GitTabExpansion.ps1 | select -last 18)
============================== GitTabExpansion.ps1 ================= =============

if (Test-Path Function:\TabExpansion) {
    Rename-Item Function:\TabExpansion TabExpansionBackup
}

function TabExpansion($line, $lastWord) {
    $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()

    switch -regex ($lastBlock) {
        # Execute git tab completion for all git-related commands
        "^$(Get-AliasPattern git) (.*)" { GitTabExpansion $lastBlock }
        "^$(Get-AliasPattern tgit) (.*)" { GitTabExpansion $lastBlock }

        # Fall back on existing tab expansion
        default { if (Test-Path Function:\TabExpansionBackup) { TabExpansionBackup $line $lastWord } }
    }
}

=============================================== ================================

重新定义TabExpansionBackup(原始TabExpansion)

function TabExpansionBackup {
    ...

    ### Resolve Command name & parameter name

    ...

    ### Currently target is Get-Alias & "-Name" parameter

    ...
}