-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAdd-DynamicParameters.ps1
77 lines (66 loc) · 2.73 KB
/
Add-DynamicParameters.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Function Add-DynamicParameters{
<#
.SYNOPSIS
Add-DynamicParameters is a function which adds dynamic parameters based on the name value pair hashtable
.DESCRIPTION
Add-DynamicParameters is a function which adds dynamic parameters based on the name value pair hashtable
.Notes
Author: Gurpreet Singh Jutla
.EXAMPLE
C:\PS> Add-DynamicParameters -parameterTable @{
"ForeColor" = @{
Value = ([enum]::GetValues([System.ConsoleColor]))
IsMandatory = $false
}
"BGColor" = @{
Value = ([enum]::GetValues([System.ConsoleColor]))
IsMandatory = $false
}
}
In the above example the Add-DynamicParameters will create a dictionary collection of two parameters naming ForeColor and BG Color both having a set of
system color collection. The IsMandatory field specifies if the parameter is mandatory or not
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $True)]
[Hashtable]$parameterTable
)
#$colors = [enum]::GetValues([System.ConsoleColor])
$RuntimeParamDic = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
foreach($key in $parameterTable.keys){
$ParamAttrib = New-Object System.Management.Automation.ParameterAttribute
$ParamAttrib.Mandatory = $parameterTable[$key].IsMandatory
$ParamAttrib.ParameterSetName = '__AllParameterSets'
$AttribColl = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$AttribColl.Add($ParamAttrib)
$AttribColl.Add((New-Object System.Management.Automation.ValidateSetAttribute($parameterTable[$key].ValidateSet)))
$RuntimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter($key, [string], $AttribColl)
$RuntimeParamDic.Add($key, $RuntimeParam)
}
return $RuntimeParamDic
}
#sample usage
function Test-DynamicValidateSet {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[ValidateSet('Static1','Static2','Static3','Static4','Static5')]
[String]$Test
)
DynamicParam{
Add-DynamicParameters -parameterTable @{
"ForeColor" = @{
ValidateSet = ([enum]::GetValues([System.ConsoleColor]))
IsMandatory = $false
}
"BGColor" = @{
ValidateSet = ([enum]::GetValues([System.ConsoleColor]))
IsMandatory = $false
}
}
}
Process {
Write-Host ("Test Parameter: {0}`nBGColor: {1}`nForecolor: {2}" -f $Test, $PSBoundParameters.BGColor, $PSBoundParameters.ForeColor)
}
}
#Try the function and see what parameters are displayed