将ValidateSet与从CSV文件加载的内容一起使用 [英] Use ValidateSet with the contents loaded from a CSV file

查看:90
本文介绍了将ValidateSet与从CSV文件加载的内容一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆