Create multiple List Items with a CSV file using Invoke-PnPSPRestMethod

Did you know that there’s also a PnP PowerShell command that will use a REST request? Meaning we’ve got a different syntax, (sometimes) better performance, but the same results.

In this blog post, we’ll create items in a SharePoint Online list using the Invoke-PnPSPRestMethod by importing a CSV file. Let’s go!  🚀

ℹ️. If you’re not familiar with SharePoint REST API, have a look at the official documentation.

 

The CSV file

Nothing specific in the .csv file compared to other methods of creating items.
For this example, I just have a Title and two (2) other columns.

 

The Script

The beginning will look similar to what we (admins) are used to with PowerShell.
We connect to the target site (or admin center if multiple sites to loop through) using Connect-PnPOnline, import our .csv file, and then we create a foreach loop to go through all the rows in the file.

Here, we’ll directly create a hashtable referencing our column headers & items inside the loop, store that in a variable so we can then use this variable in the Invoke-PnPSPRestMethod cmdlet.

By using this cmdlet, we need to specify the method we’d like our script to action: POST.
We also need to grab our list: /_api/web/lists/GetByTitle(‘<YOUR-LIST>’)/items

Here’s what it’d look like:

$csvFile = Import-Csv -Path "<YOUR-FILE-PATH.csv>"

foreach($item in $csvFile){
   $eachItem = @{
       Title = $item.Title
       OfficeLocation = $item.OfficeLocation
       CUCountry = $item.CUCountry
   }

   Invoke-PnPSPRestMethod -Method Post -Url "/_api/web/lists/GetByTitle('PnP List')/items" -Content $eachItem

} #end of foreach loop

Note that the Invoke-PnPSPRestMethod command is inside the loop.

 

Thanks for reading!  🙂

 

 

 

Leave a Reply

%d bloggers like this: