PowerShell ValidateSet [英] PowerShell ValidateSet
问题描述
我真的很喜欢 ValidateSet
的工作方式。在PowerShell ISE中键入Cmdlet时,它会将选项建议为列表。
I really like the way that ValidateSet
works. It proposes the options as a list while you type your Cmdlet in the PowerShell ISE.
我想知道是否可以从CSV文件( Import-CSV
)中检索值,在 Param
块中使用它们,以便在构造Cmdlet参数时它们在PowerShell ISE的下拉框中可用?与 $ Type
现在有效,但是与导入文件中的值相同。
I would like to know if it's possible to retrieve values from a CSV-file (Import-CSV
) and use them in the Param
block so they become available in the drop down box of the PowerShell ISE when constructing the Cmdlet arguments? A bit in the same way that $Type
works now, but then with values from the import file.
Function New-Name {
Param (
[parameter(Position=0, Mandatory=$true)]
[ValidateSet('Mailbox','Distribution','Folder','Role')]
[String]$Type,
[parameter(Position=1,Mandatory=$true)]
[String]$Name
)
Process { 'Foo' }
}
推荐答案
以下是您可以从以下开始:
Here is something you can start with:
function New-Name {
param (
[parameter(Position=0, Mandatory=$true)]
[String]$Name
)
dynamicparam {
$attributes = new-object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "__AllParameterSets"
$attributes.Mandatory = $true
$attributeCollection = new-object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$values = @('MailBox', 'Tralala', 'Trilili') # your Import-Csv here
$ValidateSet = new-object System.Management.Automation.ValidateSetAttribute($values)
$attributeCollection.Add($ValidateSet)
$dynParam1 = new-object -Type System.Management.Automation.RuntimeDefinedParameter("Type", [string], $attributeCollection)
$paramDictionary = new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("Type", $dynParam1)
return $paramDictionary
}
process { 'Foo' }
}
学分必须到期,这主要来自以下文章。
Credits where credits are due, this largely comes from the following article from the Scripting Guy. The code isn't pretty, but it does what you want.
这篇关于PowerShell ValidateSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!