Use ValidateSet with the contents loaded from a CSV file

本秂侑毒 提交于 2019-12-31 11:01:45

问题


I really like the way that ValidateSet works. It proposes the options as a list while you type your Cmdlet in the PowerShell ISE.

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' }
}

回答1:


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.




回答2:


I prefer TabExpansion++ module though this doesn't technically validate, it has some nice functionality...

Here's an example of an msbuild overloaded command to add some intellisense for projects

Register-ArgumentCompleter -CommandName "msbuild" -ParameterName "target" -ScriptBlock {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)

    $projectName = $fakeBoundParameter['project']
    $projectFile = Join-Path (Get-Location) $projectName
    $projectXml = [xml](Get-Content $projectFile)

    $targets = $projectXml.Project.Target | Where-Object { $_.Name.ToString().StartsWith($wordToComplete) }
    foreach($target in $projectXml.Project.Target)
    {
        New-CompletionResult -CompletionText "$($target.Name)"
    }
}


来源:https://stackoverflow.com/questions/25177744/use-validateset-with-the-contents-loaded-from-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!