Get all parameters passed to a function in PowerShell

I have a function like the following. It generates a string according to the passed parameters.

function createSentenceAccordingly {
Param([Parameter(mandatory = $false)] [String] $name,
      [Parameter(mandatory = $false)] [String] $address,
      [Parameter(mandatory = $false)] [String] $zipcode,
      [Parameter(mandatory = $false)] [String] $city,
      [Parameter(mandatory = $false)] [String] $state)

    $stringRequired = "Hi,"

    if($name){
        $stringRequired += "$name, "
    }
    if($address){
        $stringRequired += "You live at $address, "
    }
    if($zipcode){
        $stringRequired += "in the zipcode:$zipcode, "
    }
    if($name){
        $stringRequired += "in the city:$city, "
    }
    if($name){
        $stringRequired += "in the state: $state."
    }

    return $stringRequired
}

      

So basically the function returns something depending on the parameters passed. I wanted to avoid if loops as much as possible and access all parameters immediately.

Can I access all the parameters in an array or hashmap? Since I have to use named parameters, $ args cannot be used here. If I could access all the parameters at once (maybe in an array like $ args or hashamp), my plan is to use that to create a returnstring dynamically.

In the future, the parameters for the function will increase a lot and I don't want to keep writing if there are loops for every additional parameter.

Thanks in advance,:)

+3


source to share


1 answer


$PSBoundParameters

variable
is a hash table containing only those parameters that are explicitly passed to the function.

The best way for you might be to use parameter sets so that you can name specific combinations of parameters (remember to make the appropriate parameters required within these sets).



Then you can do something like:

switch ($PsCmdlet.ParameterSetName) {
    'NameOnly' {
        # Do Stuff
    }
    'NameAndZip' {
        # Do Stuff
    }
    # etc.
}

      

+7


source







All Articles