If your script accepts a single parameter that is an open-ended dictionary (hashtable) of name-value pairs:
param(
[System.Collections.IDictionary] $NamesAndValues
)
$uri = 'https:xxxxxxxx'
if ($NamesAndValues.Count) { # Non-empty dictionary was passed
# Create the collection of query-string entries.
$queryStringEntries = [System.Web.HttpUtility]::ParseQueryString('')
foreach ($param in $NamesAndValues.GetEnumerator()) {
$queryStringEntries.Add($param.Key, $param.Value)
}
# Convert the entries to a query string and append it to the URI.
$uri += '?' + $queryStringEntries.ToString()
}
Invoke-RestMethod -Uri $uri -UseDefaultCredentials
Sample invocation, using a hashtable literal:
# Results in the following URI:
# https:xxxxxxxx?parameter1=foo¶meter2=bar%2Fbaz
# Note: -NamesAndValues is positionally implied as the target parameter.
.\YourScript.ps1 @{ param1='foo'; param2='bar/baz' }
If you script has a fixed set of individual, optional parameters:
The automatic $PSBoundParameters
variable is a dictionary that contains information about what parameters were bound on invocation with what values.
Thus, the same technique for constructing the query string as above can be used, with $PSBoundParameters
serving as the input dictionary.
# Declare 3 optional (non-mandatory) parameters,
# -parameter1, -parameter2, -parameter3
param(
$parameter1,
$parameter2,
$parameter3
)
# Construct the URI based on whatever parameters were bound.
$uri = 'https:xxxxxxxx'
if ($PSBoundParameters.Count) { # At least 1 parameter was bound.
# Create the collection of query-string entries.
$queryStringEntries = [System.Web.HttpUtility]::ParseQueryString('')
foreach ($param in $PSBoundParameters.GetEnumerator()) {
$queryStringEntries.Add($param.Key, $param.Value)
}
# Convert the entries to a query string and append it to the URI.
$uri += '?' + $queryStringEntries.ToString()
}
Invoke-RestMethod -Uri $uri -UseDefaultCredentials
Sample invocation:
# Results in the following URI:
# https:xxxxxxxx?parameter1=foo¶meter2=bar%2Fbaz
.\YourScript.ps1 -parameter1 'foo' -parameter2 'bar/baz'