将ValidateSet与从CSV文件加载的内容一起使用 [英] Use ValidateSet with the contents loaded from a CSV file
问题描述
我真的很喜欢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' }
}
推荐答案
您可以从这里开始:
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.
这篇关于将ValidateSet与从CSV文件加载的内容一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!