Search code examples
powershellparameters

POWERSHELL - Handling Parameter Sets Gracefully


I have a function:

Function Get-CMAPICollection {
[CmdletBinding()]
param (
    [parameter(ValueFromPipeline = $true, Mandatory = $True, ParameterSetName = "ByName")]
    [string]$collectionName,
    [parameter(ValueFromPipeline = $true, Mandatory = $True, ParameterSetName = "ById")]
    [string]$collectionId
)

If ($collectionName) {
    $URI = "https://$($CMAPI.cmServer)/AdminService/wmi/SMS_Collection?`$filter=Name eq '$collectionName'"
    
}

If ($collectionId) {
    $URI = "https://$($CMAPI.cmServer)/AdminService/wmi/SMS_Collection?`$filter=CollectionId eq '$collectionId'"
}

(Send-CMAPIRequest -method GET -URI $uri).Value

}

Which all works fine.

I'm wondering if there is a better way to dynamically handle the parameters in the function than a bunch of 'If' statements.

My concern is that if I need to add a whole lot of parameter sets, the functions itself is going to have a whole bunch of 'If' statements cluttering up the place.

No matter how far I abstract it out, there is still an 'If' collecionName or 'If' collectionId.

Thanks!


Solution

  • As always, literally minutes after posting I have found the answer. Provided by this answer here:

    Which parameter set has been used?

    Using the variable:

    $PSCmdlet.ParameterSetName
    

    and then a switch statement will reduce the requirement for IF statements.

    I suppose this is a duplicate, however I think the question and answer provide some good examples and information.

    Fixed function:

    Function Get-CMAPICollection {
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline = $true, Mandatory = $True, ParameterSetName = "ByName")]
        [string]$collectionName,
        [parameter(ValueFromPipeline = $true, Mandatory = $True, ParameterSetName = "ById")]
        [string]$collectionId
    )
    
    switch ($PSCmdlet.ParameterSetName) {
        byName { $URI = "https://$($CMAPI.cmServer)/AdminService/wmi/SMS_Collection?`$filter=Name eq '$collectionName'" }
        ById { $URI = "https://$($CMAPI.cmServer)/AdminService/wmi/SMS_Collection?`$filter=CollectionId eq '$collectionId'" }
    }
    
    (Send-CMAPIRequest -method GET -URI $uri).Value
    

    }