如何在 PowerShell 3.0 中实现 PowerShell 函数或 cmdlet(例如 Get-Service 和 Get-Process)的参数选项卡补全?
我发现验证集适用于已知列表,但我想按需生成列表。
亚当·德里斯科尔暗示这是可能的对于 cmdlet,但不幸的是没有详细说明。
特雷弗·沙利文展示了一种技术对于函数,但据我了解,他的代码仅在定义函数时生成列表。
我为此困惑了一段时间,因为我也想做同样的事情。我整理了一些我非常满意的东西。
您可以从 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 文件,制表符完成行为将立即更改;您不必重新导入该函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)