I'm trying to build a script that has 3 parameters to get the data from an API.
How can I associate the below url with a matrix of combinations?
Invoke-RestMethod -Uri "https:xxxxxxxx?parameter1=$parameter1¶meter2=$parameter2¶meter3=$parameter3" - UseDefaultCredentials
Thanks
CodePudding user response:
("x","y","z"),("p","q","r"),("a","b","c") | ForEach-Object {"https://blah?p1={0}&p2={1}=&p3={2}" -f @($_)}
CodePudding user response:
If your script accepts a single parameter that is an open-ended dictionary (hashtable) of parameter name-value pairs:
- Construct a query string from the dictionary's name-value pairs with the help of
[System.Web.HttpUtility]::ParseQueryString()
, using the technique shown in this answer, and append it to the target URI.
param(
[System.Collections.IDictionary] $NamesAndValues
)
$uri = 'https:xxxxxxxx'
if ($NamesAndValues.Count) { # 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:
# Results in the following URI:
# https:xxxxxxxx?parameter1=foo¶meter2=bar/baz
# 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/baz
.\YourScript.ps1 -parameter1 'foo' -parameter2 'bar/baz'