Author Posts

September 18, 2014 at 6:56 pm

I have an advanced function I have been working on that looks something like this:

{Function Do-Something
{
[cmdletbinding()] 
     
    Param  
    (              
         [Parameter(Mandatory=$true, 
         [ValidateSet('Yes', 'No', 'Y', 'N', IgnoreCase = $true)]   
         [string[]]$Param1,
         
         [Parameter(Mandatory=$true,  
         [ValidateSet('Yes', 'No', 'Y', 'N', IgnoreCase = $true)] 
         [string[]]$Param2,

         [Parameter(Mandatory=$true,   
         [ValidateSet('Yes', 'No', 'Y', 'N', IgnoreCase = $true)] 
         [string[]]$Param3
    )  

 Begin {}

 Process 
 {
   


 }
}}

My question is, how do I get the values such as "Yes", "Y", "No", and "N" that's located in the [ValidateSet()] validation attribute processed correctly without having to use multiple "If" and "ElseIf" statements.

For instance, I want to avoid the following, because I know there is a faster and more efficient way (less typing) to do it:

If ($param1 -match "Yes" -or "Y" -and $param2 -match "Yes" -or "Y" -and $param3 -match "Yes" -or "Y")

{

#Do something here

}

ElseIf ($param1 -match "No" -or "N" -and $param2 -match "Yes" -or "Y" -and $param3 -match "Yes" -or "Y")

{

#Do something

}

I was reading that splatting may help me here, but I am new to the splatting technique and need some help with this one.

I appreciate any help that anyone can offer.

Thanks

September 18, 2014 at 7:24 pm

Well, in this specific case, I'd probably just look at the first letter of each parameter, since you know that they can only be Y/Yes or N/No. That would cut down on half of your conditions:

if ($Param1 -like 'Y*' -and $Param2 -like 'Y*' -and $Param3 -like 'Y*')
{
    # do something
}

The fact that you're defining these parameters as arrays throws a wrench in the works, though... then these conditions are really saying "if any of the elements in the array are Y or Yes for all three arrays, do something."

Personally, I would just use switch parameters here, or at the least, booleans. Those already do a good job of indicating "yes/no" style values (true/false):

function Do-Something
{
    [CmdletBinding()]
    Param
    (
        [switch] $Param1,
        [switch] $Param2,
        [switch] $Param3
    )

    if ($Param1 -and $Param2 -and $Param3)
    {
        # Do Something
    }
}

September 18, 2014 at 8:44 pm

Ahh the switch parameter, of course. I've used them before on several occasions a while back. Had a brain fart there man.

Thanks

September 18, 2014 at 9:12 pm

To use the switch parameter, would I remove the "Mandatory=$true" attribute?

September 19, 2014 at 3:23 am

Yes. Mandatory switches don't make much sense. 🙂

September 20, 2014 at 9:11 pm

Of course they don't, just wanted confirmation.

Thanks man