Search code examples
powershellpowershell-cmdletwindows-terminalinvoke-restmethod

How to use Invoke-RestMethod with Import-Csv to loop through URLs


I'm attempting to dynamically create about 50 QR Codes using GoQR.me's API. I have all the source and destination URLs in a CSV file QRCodes.csv formatted as:

source, destination
https://api.qrservers.com/v1/..., C:\Users\...\QR1.png

I originally attempted to use PowerShell's Start-BitsTransfer

Import-Csv QRCodes.csv | Start-BitsTransfer

But because the server doesn't return Content-Length in the header of the HTTP reply, Start-BitsTransfer fails.

How would I do something similar using Invoke-RestMethod or Invoke-WebReqest instead? I can easily do one request at a time, but can't figure out how to loop through the CSV. (I'm a relative noob at PowerShell)


Solution

  • Assuming the source cell contains all the data required by the API endpoint, use ForEach-Object to iterate over the list of CSV records and then call Invoke-WebRequest:

    Import-Csv QRCodes.csv | ForEach-Object {
        Invoke-WebRequest -Uri $_.source -OutFile $_.destination
    }