gpt4 book ai didi

powershell - 无法在 Validateset 中使用预定义数组 - Powershell

转载 作者:行者123 更新时间:2023-12-03 16:29:50 25 4
gpt4 key购买 nike

我正在寻找一种方法来制作接收参数的 cmdlet,并且在键入时,它会根据预定义的选项数组提示完成建议。
我正在尝试这样的事情:

$vf = @('Veg', 'Fruit')
function Test-ArgumentCompleter {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateSet($vf)]
$Arg
)
}
预期的结果应该是:
编写“Test-ArgumentCompleter F”时,单击 tub 按钮后,F 自动完成为 Fruit。

最佳答案

补充来自 @mklement0 的回答和 @Mathias , 使用 dynamic parameters :

$vf = 'Veg', 'Fruit'

function Test-ArgumentCompleter {
[CmdletBinding()]
param ()
DynamicParam {
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$AttributeCollection.Add($ParameterAttribute)
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($vf)
$AttributeCollection.Add($ValidateSetAttribute)
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter('Arg', [string], $AttributeCollection)
$RuntimeParameterDictionary.Add('Arg', $RuntimeParameter)
return $RuntimeParameterDictionary
}
}
根据您希望如何预定义参数值,您还可以使用 dynamic validateSet values :
Class vfValues : System.Management.Automation.IValidateSetValuesGenerator {
[String[]] GetValidValues() { return 'Veg', 'Fruit' }
}

function Test-ArgumentCompleter {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateSet([vfValues])]$Arg
)
}

note: The IValidateSetValuesGenerator class [read: interface] was introduced in PowerShell 6.0

关于powershell - 无法在 Validateset 中使用预定义数组 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67356762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com