Last active
January 6, 2017 19:35
-
-
Save derekmwright/91504970eb876ca4ff9c6c5714ada2ef to your computer and use it in GitHub Desktop.
PowerShell Define Common Parameters to be Used Across Multiple Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Define Parameters in the following ArrayList | |
# and pass to GenerateParameters | |
# Note: does not support more advanced features like param sets and validations | |
# ...yet | |
$def = @( | |
@{ | |
"Name"="Name"; | |
"Type"=[String]; | |
"Properties"=@( | |
@{ | |
"Mandatory"=$true; | |
"Position"=0; | |
} | |
) | |
},@{ | |
"Name"="Credential"; | |
"Type"=[PSCredential] | |
"Properties"=@( | |
@{ | |
"Mandatory"=$true; | |
"Position"=1; | |
} | |
) | |
} | |
) | |
function GenerateParameters($definition) | |
{ | |
$params = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary | |
$definition | %{ | |
$attrs = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] | |
$_.Properties | %{ | |
$attr = New-Object -Type Parameter | |
$props = $_ | |
$_.Keys | %{ | |
$attr.($_) = $props.Item($_) | |
} | |
$attrs.Add($attr) | |
} | |
$params.Add( | |
$_.Name, | |
(New-Object -Type System.Management.Automation.RuntimeDefinedParameter( | |
$_.Name, | |
$_.Type, | |
$attrs | |
)) | |
) | |
} | |
return $params | |
} | |
# The following functions will have matching parameters | |
function TestCmd | |
{ | |
[CmdletBinding()] | |
param() | |
DynamicParam{ | |
GenerateParameters($def) | |
} | |
} | |
function TestCmdOther | |
{ | |
[CmdletBinding()] | |
param() | |
DynamicParam{ | |
GenerateParameters($def) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment