Home > database >  PowerShell Script - Export Data With For Cycle
PowerShell Script - Export Data With For Cycle

Time:07-13

Good evening guys,

I need your help because I'm not getting the expected result. I need to create a powershell script that stores the result of the for cycle that has a variable called offset and that adds the value 100 in the 70 times that the cycle runs and starts at the value 101

In the final result we will store the data of:

  • https://test/api/offers?api_key=123456&max=100
  • https://test/api/offers?api_key=123456&max=100&offset=101
  • https://test/api/offers?api_key=123456&max=100&offset=201
  • https://test/api/offers?api_key=123456&max=100&offset=301
  • .
  • .
  • .
  • https://test/api/offers?api_key=123456&max=100&offset=7001
$response = Invoke-RestMethod -Uri 'https://test/api/offers?api_key=123456&max=100' -Method 'GET' -ContentType 'application/json'
$concat = $response.offers

For ($i=101; $i -le 70; $i  ) {
$response = Invoke-RestMethod -Uri 'https://test/api/offers?api_key=123456&max=100&offset=$($i 100)" -Method 'GET' -ContentType 'application/json'
$concat = $response.offers
$concat = $concat   $response.offers
}
$concat  | ConvertTo-Json | Out-File "C:\TEMP\API_RESULT.json" -Encoding bigendianunicode

Thanks

CodePudding user response:

Well, let's start with the logic behind a For loop.

For (<define a start point>; <define a stop condition>; <define how to iterate>){<loop content>}

Right now you have:

For ($i=101; $i -le 70; $i  )

So it starts with $i set to 101, and will run the loop while $i is less than or equal to (-le) 70, and each time the loop finishes it increments $i by 1 ($i ). This tells me that it will immediately stop, because your end condition is that $i is greater than 70, and $i starts off at 101, which is very much greater than 70. So, how do we fix this? We give it the values you really want.

For($i = 101; $i -le 7001; $i = $i   100)

Now inside your loop you can just reference $i instead of $i 100. Also, you are setting (not modifying) $concat each time the loop passes, so in the end you will only have data for the last time the loop ran. A better way to do it is to just output the data, and capture all output for the loop in a variable.

$response = Invoke-RestMethod -Uri 'https://test/api/offers?api_key=123456&max=100' -Method 'GET' -ContentType 'application/json'
[array]$Results = $response.offers

$Results  = For ($i=101; $i -le 70; $i  ) {
    $response = Invoke-RestMethod -Uri "https://test/api/offers?api_key=123456&max=100&offset=$i" -Method 'GET' -ContentType 'application/json'
    $response.offers
}

$Results | ConvertTo-Json | Out-File "C:\TEMP\API_RESULT.json" -Encoding bigendianunicode

Now, that's not tested, but if your original code at least kind of worked (at least for the first line) then this should do what you want.

  • Related