PowerShell ValidateSet

Dar*_*te1 13 csv validation parameters powershell

我真的很喜欢这种方式ValidateSet.当您在PowerShell ISE中键入Cmdlet时,它会将选项作为列表提出.

我想知道是否可以从CSV文件中检索值Import-CSV并在Param块中使用它们,以便在构造Cmdlet参数时它们可以在PowerShell ISE的下拉框中使用?有点像$Type现在一样工作,但随后使用导入文件中的值.

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' }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ant 19

您可以从以下内容开始:

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' }
}
Run Code Online (Sandbox Code Playgroud)

学分到期的学分,主要来自脚本专家的以下文章.代码并不漂亮,但它可以满足您的需求.

完成