Friday, March 1, 2024
HomePowershellMastering PowerShell Parameter Validation with Dynamic Strategies

Mastering PowerShell Parameter Validation with Dynamic Strategies


One of many coolest but advanced options of superior features in PowerShell is dynamic parameters and utilizing that characteristic to carry out PowerShell parameter validation. Dynamic parameters take your typical operate parameters to an entire new stage.

Have you ever ever had a time once you created a sophisticated operate and wished your parameters to rely on one thing else; to dynamically be created primarily based on the standards you select at runtime?

How about wanting Powershell parameter validation like constructing a PowerShell ValidateSet array offering tab-completion on a parameter not primarily based on a static set of stings however generated at runtime? These are each doable with dynamic parameters.


This publish is a part of the PowerShell Running a blog Week (#PSBlogWeek) collection on Home windows PowerShell Superior Capabilities, a collection of coordinated posts designed to supply a complete view of a specific subject.

On this collection, we even have:

To counsel a PowerShell Running a blog Week subject, go away a remark or tweet it to us with the #PSBlogWeek hashtag.


There are a few alternative ways to make use of dynamic parameters that I’ve seen. The primary is the way in which that Ben Ten wrote about them on PowerShell Journal. Utilizing this methodology, Ben was in a position to create parameters on the fly primarily based on if a special parameter was used. Personally, I’ve by no means had a necessity to do that.

I actually like utilizing dynamic parameters as a approach to validate enter primarily based on some standards which might be out there at runtime. This manner I can write a script that gathers info on-the-fly which permits me the gorgeous parameter tab-completion everyone knows and love.

Let’s go over an instance on the best way to create Powershell parameter validation primarily based on information in a folder.

“Regular” superior operate parameters assist you to use a number of Validate choices. You may validate the variety of arguments a parameter can settle for, the minimal and most size of a parameter argument, a set of choices in an array, matching a regex string or a scriptblock and extra. What I’m on the lookout for right here is to make use of the ValidateSet attribute for the tab-completion.

Tab completion in PowerShell
Tab completion in PowerShell

You’ll discover within the instance above I’m utilizing the Get-Merchandise cmdlet and the default parameters for tab-completion which is to be anticipated. I need that performance however I wish to tab-complete my very own arguments so let’s create a easy operate to try this.

The PowerShell ValidateSet parameter validation attribute
The PowerShell ValidateSet parameter validation attribute

You’ll discover that I’ve highlighted the validation attribute that can permit us to tab-complete the MyParameter argument. Now we’re in a position to get customized parameter argument tab-completion utilizing the values specified within the PowerShell ValidateSet array attribute.

Tab-completion with dynamic parameters
Tab-completion with dynamic parameters

However now what if I need my tab-completion choices to be generated on-the-fly primarily based on another standards somewhat than a static record? The one possibility is to make use of dynamic parameters. In my instance, I wish to tab-complete a listing of information in a specific folder at run-time.

To get this carried out I’ll be utilizing a dynamic parameter which is able to run Get-ChildItem every time I attempt to tab-complete the MyParameter parameter.

With that being mentioned, let’s make the ValidateSet attribute of the MyParameter parameter dynamic, we could?

The primary distinction between a typical parameter and a dynamic parameter that you simply’ll discover is dynamic parameter are in their very own block.

[CmdletBinding()]
param()
DynamicParam {

}

Making a Dynamic Powershell Parameter Validation the Laborious Method

Contained in the DynamicParam block is the place the magic occurs. And the magic does take some time to wrap your head round.

A dynamic parameter is, in a way, a System.Administration.Automation.RuntimeDefinedParameterDictionary object with a number of System.Administration.Automation.RuntimeDefinedParameter objects inside it. However it’s not fairly that straightforward. Let’s break it down.

  1. First, instantiate a brand new System.Administration.Automation.RuntimeDefinedParameterDictionary object to make use of as a container for the a number of parameters we’ll be including to it utilizing
$RuntimeParamDic = New-Object System.Administration.Automation.RuntimeDefinedParameterDictionary.

2. Subsequent, create the System.Collections.ObjectModel.Assortment prepped to include System.Attribute objects.

$AttribColl = New-Object System.Collections.ObjectModel.Assortment[System.Attribute].

3. Now instantiate a System.Administration.Automation.ParameterAttribute object which is able to maintain the entire parameter attributes we’re used to. In our occasion, I’m defining my parameter to be in all of the parameter units and settle for pipeline enter by a pipeline object and by property title.

$ParamAttrib = New-Object System.Administration.Automation.ParameterAttribute
$ParamAttrib.Necessary = $Necessary.IsPresent
$ParamAttrib.ParameterSetName="__AllParameterSets"
$ParamAttrib.ValueFromPipeline = $ValueFromPipeline.IsPresent
$ParamAttrib.ValueFromPipelineByPropertyName = $ValueFromPipelineByPropertyName.IsPresent

4. Add our parameter attribute set to the gathering we instantiated above.

$AttribColl.Add($ParamAttrib)

5. As a result of I’m utilizing this dynamic parameter to construct a PowerShell ValidateSet array for parameter validation I need to additionally embrace a System.Administration.Automation.ValidateSetAttribute object inside our attribute assortment. That is the place you outline the code to really create the values that permits us to tab-complete the parameter arguments.

$AttribColl.Add((New-Object System.Administration.Automation.ValidateSetAttribute((Get-ChildItem C:TheAwesome -File | Choose-Object -ExpandProperty Title))))

6. We then must instantiate a System.Administration.Automation.RuntimeDefinedParameter object utilizing the parameter title, it’s kind and the attribute assortment we’ve been including stuff to.

$RuntimeParam = New-Object System.Administration.Automation.RuntimeDefinedParameter('MyParameter', [string], $AttribColl)

7. As soon as the run time parameter is completed we then come again to that unique dictionary object we instantiated earlier utilizing the parameter title and the runtime parameter object we created.

$RuntimeParamDic.Add('MyParameter', $RuntimeParam)

8. We are able to then return this runtime dictionary object again to the dynamic parameter block and we’re carried out!

Are your eyes glazing over but? Mine was once I first tried to determine this out.

Being the lazy admin I’m I created a operate referred to as New-ValidationDynamicParam that does all this be just right for you creating the PowerShell ValidateSet array. Merely cross within the parameter title, the attributes you’d just like the parameter to have and the code you’ll be utilizing to create the validation and also you’re carried out! The operate does the remaining.

Making a Dynamic ValidateSet Array Parameter the Simple Method

New-ValidationDynamicParam -Title 'MyParameter' -Necessary -ValidateSetOptions (Get-ChildItem C:TheAwesome -File | Choose-Object -ExpandProperty Title)

My ache is your achieve, individuals!

Now, with our dynamic validation parameter created, let’s take it for check drive.

I’ve bought some information in a listing on my pc that I solely wish to be handed to the MyParameterparameter.

Sample text files
Pattern textual content information

Now all I’ve to do is run our script and voila! I’m now solely in a position to make use of the file names as parameter arguments and they’re up to date because the information comes out and in of the folder!

Using the dynamic parameter creation script
Utilizing the dynamic parameter creation script
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments