0

In my script , I am passing list of components need to taken build

    [ValidateSet("InstalComponent","CoreComponent","SDKComponent","ServiceComponent","TimeComponent")]
   $Components=@("InstalComponent","CoreComponent"),

From time to time we are adding new component and the list is too long. If there is a way like passing via file "GEt-content Components.txt". It will be of good. Is there any way to set like this?

Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230
  • I just answered a question regarding dynamic validationsets for powershell parameters in http://stackoverflow.com/questions/30111408/powershell-multiple-parameters-for-a-tabexpansion-argumentcompleter – TheMadTechnician May 08 '15 at 05:03

3 Answers3

1

One option is to create an [enum] from the file contents, then cast the parameter as that type:

@(
   "InstalComponent",
   "CoreComponent",
   "SDKComponent",
   "ServiceComponent",
   "TimeComponent") | 
   set-content Components.txt


Add-Type -TypeDefinition @"
   public enum MyComponents
   {
     $(((Get-Content .\Components.txt) -join ', ').split())
   }
"@

function test
{
  param ( [MyComponents[]]$Components)
  $Components
}

Creating and using enums in Powershell

mjolinor
  • 66,130
  • 7
  • 114
  • 135
1

I may not quite understand the question, but you can validate a parameter using ValidateScript like this: Create a file "Components.txt" with a line for each option on separate lines, with no quotes or commas. Then validate like this:

param(
    [ValidateScript({ 
        $Components = Get-Content .\Components.txt
        $Components.Contains($_)
    })
    ]
    [String]$Component)
...
DeNelo
  • 11
  • 2
0

Short answer: no.

Longer answer: If you must validate a parameter using a configurable set of values you can still do it the old way by putting the validation at the beginning of the function body:

function Foo {
  Param(
    [Parameter()]$Bar
  )

  $validSet = Get-Content 'C:\path\to\components.txt'
  if ($validSet -notcontains $Bar) {
    throw "Invalid argument for parameter -Bar: $Bar"
  }

  ...
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328