Please help me loop through a CSV. RRS feed

  • Question

  • I have a script that pushes $firstname $lastname to our documentation portal via API (See code below). How can I do it so that $firtname $lastname is actually extracted from a pre-determined users.csv file which will have two columns firstname and lastname? 

    Thank you~!

    See my code below:

    $firstname = "john"
    $lastname =  "smith"
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add("X-API-KEY", 'ITG.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
    $headers.Add("Content-Type" , 'application/vnd.api+json')
    $body = @{
     data = @{
       type = 'flexible-assets'
       attributes =  @{
         organization_id = 708164
         flexible_asset_type_id = 122389
         traits = @{
           firstname = $firstname
            lastname = $lastname

    } | convertto-json -depth 4
    invoke-RestMethod -Uri https://api.itglue.com/flexible_assets -Method POST -Body $body -Headers $headers

    • Edited by hydec Wednesday, March 20, 2019 3:13 AM
    Wednesday, March 20, 2019 3:09 AM

All replies

  • Something similar to below reads values from a CSV file.

    $Lines = Import-Csv "C:\Scripts\Users.csv"
    ForEach ($Line In $Lines)
        $FirstName = $Line.FirstName
        $LastName = $Line.LastName
        # Do something with the values on this line.
    Edit: This assumes that the CSV file has a header line defining the fields "FirstName" and "LastName". See the help for the Import-Csv cmdlet.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Wednesday, March 20, 2019 3:16 AM
  • Hi Richard, Thanks for your reply. I saw a tutorial like that online but was a bit confused. Where would I insert that loop in my code? The only time i reference my $firstname and $lastname is below the traits = @{ line. Thanks.
    Wednesday, March 20, 2019 3:33 AM
  • Assuming the invoke-RestMethod statement is to run once per user, your code (except the lines assigning hard coded values to $firstname and $lastname) would be placed where I included the comment (the line starting with "#"). Then your code will run once for each line in the CSV file.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Wednesday, March 20, 2019 3:46 AM
  • Hi,

    Was your issue resolved?

    If you resolved it using our solution, please "mark it as answer" to help other community members find the helpful reply quickly.

    If you resolve it using your own solution, please share your experience and solution here. It will be very beneficial for other community members who have similar questions.

    If no, please reply and tell us the current situation in order to provide further help.

    Best Regards,


    Just do it.

    Wednesday, March 27, 2019 6:32 AM