I have a function as following. It generates a string as per the parameters passed.
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 upon the parameters passed. I wanted to avoid the if loops as much as possible and access all the parameters at once.
Can I access all the parameters in an array or a hashmap ? As I should be using named parameters, $args cannot be used here. If I could access all the parameters at once (may be in an array like $args or a hashamp), my plan is to use that to create the returnstring dynamically.
In the future, the parameters for the function will increase a lot and I donot want to keep on writing if loops for each additional parameter.
Thanks in advance, :)
The $PSBoundParameters
variable is a hashtable that contains only the parameters explicitly passed to the function.
A better way for what you want might be to use parameter sets so that you can name specific combinations of parameters (don't forget to make the appropriate parameters mandatory within those sets).
Then you can do something like:
switch ($PsCmdlet.ParameterSetName) {
'NameOnly' {
# Do Stuff
}
'NameAndZip' {
# Do Stuff
}
# etc.
}