Function parameters and Parameter Sets

In the latest incarnation of my Get-ADGroupmembership function I’ve used Parameter Sets to distinguish between input received from the user.
In the Param() statement you can define which parameters your function accepts. But what if you want different processing for different input types?

For Get-ADGroupmembership I want to accept String input as well as ADUser and ADGroup Objects as input. With ADUser and ADGroup Objects I can start querying Active Directory right away, but this is not the case with String input.
The String input needs to be processed so I get either an ADUser Object or an ADGroup Object.

In the previous version of my function I simply perform a check on the Object Type of whatever input I get and match it with input types I’m willing to work with. But it seems that PowerShell has a more elegant way of dealing with this problem: Parameter Sets.

In the sample above you can see I’ve defined three different parameter sets. One for String input, one for ADUser input and one for ADGroup input.
In the CmdletBinding() statement I’ve set parameter set ‘p1′ as default set. This means that any input that doesn’t match ADUser or ADGroup will be cast as String and processed as such.
Also note that the switch ‘$Group’ is also defined as member of the parameter set ‘p1′. If the switch ‘-Group’ is used the input will always be cast as String, even if it really is an ADUser Object or ADGroup Object.

You may notice that for ADUser and ADGroup I’ve used the full assembly names:¬†Microsoft.ActiveDirectory.Management.ADUser and¬†Microsoft.ActiveDirectory.Management.ADGroup.
There is a caveat here. If this assembly isn’t loaded then calling the function will result in an error, though only on the first call. So in order to make this work without an error message about missing assemblies I first have to load the assembly.

If the assembly isn’t available on the system the LoadWithPartialName command will give $Null as result. In my case it will simply make my function not available.
Note that loading the assembly does not load the ActiveDirectory module.

Since I now have three parameters in my function, all of which I want to know if it came through the pipeline or not, I also need to adjust the testing for pipeline input.

There also need to be some changes in the Process block so that the parameter sets are dealt with properly.

It is a simple switch statement on the parameter set name. In the example there is no code for dealing with pipeline input, but you can see in my Get-ADGroupmembership function how to use that.

Download the test function here:
[wpfilebase tag=file id=4 tpl=simple /]

 

Tagged . Bookmark the permalink.

Comments are closed.