Created
December 9, 2014 14:38
-
-
Save lazywinadmin/4246b8df3b1d3aef2211 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#Source: Reddit (http://www.reddit.com/r/PowerShell/comments/2oqk4k/using_validateset_with_exceptions/) | |
function test { | |
# You have to use cmdletbinding for the dynamic parameter to work | |
[CmdletBinding()] | |
Param() | |
# The cool thing about this is that you can actually get really good tab completion / intellisense from doing it this way... | |
DynamicParam | |
{ | |
[string[]]$ValidServices = get-content $PSScriptRoot\services.txt | |
# Create a parameter attribute for the parameter.. | |
$paramAttribute = [System.Management.Automation.ParameterAttribute]::new() | |
$paramAttribute.ParameterSetName = "__AllParameterSets" | |
$paramAttribute.Mandatory = $true | |
# Add the validateset attribute for the parameter with the values from services... this is the really cool part | |
$validatesetAttribute = [System.Management.Automation.ValidateSetAttribute]::new($ValidServices) | |
$validatesetAttribute.IgnoreCase = $true | |
# Add the attributes to the collection of attributes | |
$attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new() | |
$attributeCollection.Add($paramAttribute) | |
$attributeCollection.Add($validatesetAttribute) | |
# Define the parameter itself | |
$dynamicParam = [System.Management.Automation.RuntimeDefinedParameter]::new("Service", [string], $attributeCollection) | |
# Create the parameter collection and return it | |
$paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new() | |
$paramDictionary.Add("Service", $dynamicParam) | |
return $paramDictionary | |
} | |
# If you use the DynamicParam block, you have to put your actual code inside a begin/process/end block | |
End | |
{ | |
if ($PSBoundParameters.ContainsKey("Service")) | |
{ | |
$Service = $PSBoundParameters["Service"] | |
} | |
$Service | |
} | |
} | |
test -service asdf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment