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.
"https://api.mysite.com/v1/data" + [string]$yearshould be("https://api.mysite.com/v1/data" + [string]$year). While in a scriptblock, the commands won't execute either, not sure if that's your intentions. YouConvertTo-Jsonis outside yourelsestatement as well.$datain yourifstatement. The error should narrow down the line that's giving you that exception. Guessing it's the one in yourforloop but, not sure if that's a typo as well$Parameters, but on the Invoke-RestMethod you use@params. The for loop is wrong too, You define a looping variable$year, but then you use$i -le $endYear, so an undefined variable$iinstead of$year. Also, since for both cases the$Headerand$ParametersHashtable are the same, why not define that only once above the if..else construct? and lastly, why not simply use-Uri "https://api.mysite.com/v1/data/year/Year/$year"??