I am working on a requirement where I have to check if the api call needs to be looped over or not. I am using the below code to accomplish this requirement. If I take out the if else block and write for either loop no loop things work as expected.
PoSh:
$Loop = "1" # 0 for no looping 1 for looping
if ($Loop -eq 1) {
$Header = @{
"authorization" = "Bearer $token"
}
#make REST API call
$Parameters = @{
Method = "GET"
Headers = $Header
ContentType = "application/json"
Body = $BodyJson
}
$startYear = 2014
$endYear = 2022
$Data = {for($year=$startYear; $i -le $endYear; $year=$year 1) {Invoke-RestMethod -Uri "https://api.mysite.com/v1/data/year/Year/" [string]$year @Parameters -DisableKeepAlive -ErrorAction Stop}} | ConvertTo-Json
}
else {Write-Output "No loop"
$Header = @{
"authorization" = "Bearer $token"
}
#make REST API call
$Parameters = @{
Method = "GET"
Headers = $Header
ContentType = "application/json"
Body = $BodyJson
}
$Data = Invoke-RestMethod -Uri "https://api.mysite.com/v1/data" @Parameters -DisableKeepAlive -ErrorAction Stop | ConvertTo-Json
}
Error:
Cannot bind parameter because parameter 'Uri' is specified more than once. To provide multiple values to parameters that can accept multiple values, use the array syntax.
CodePudding user response:
I have of course no idea what your https://api.mysite.com/v1/data
would return and if it is actually needed to convert the returned data to Json at all, but continuing from my comments, try
# make this a Boolean value for clarity
$Loop = $true # $false for no looping $true for looping
# splatting Hashtable for REST API call
$Parameters = @{
Method = "GET"
Headers = @{ "Authorization" = "Bearer $token" }
ContentType = "application/json"
Body = $BodyJson
# you can incorporate these parameters as well
DisableKeepAlive = $true
ErrorAction = 'Stop'
}
if ($Loop) {
Write-Host "Start looping.."
$startYear = 2014
$endYear = 2022
# use the $() subexpression to combine the various outputs and convert that to Json
$Data = $(for ($year = $startYear; $year -le $endYear; $year ) {
Invoke-RestMethod -Uri "https://api.mysite.com/v1/data/year/Year/$year" @Parameters
}) | ConvertTo-Json
}
else {
Write-Host "No loop"
$Data = Invoke-RestMethod -Uri "https://api.mysite.com/v1/data" @Parameters | ConvertTo-Json
}
P.S. The error you saw in your code was caused by the wrong variable you used in the for
loop with $i -le $endYear
instead of $year -le $endYear
. That and the fact that you put the whole loop inside a scriptblock made variables $startYear
and $endYear
invisible..