Home > Software design >  Invoke-RestMethod how to build a script foreach
Invoke-RestMethod how to build a script foreach

Time:08-24

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&parameter2=$parameter2&parameter3=$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:

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&parameter2=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&parameter2=bar/baz
.\YourScript.ps1 -parameter1 'foo' -parameter2 'bar/baz'
  • Related