Efficiently Add SharePoint Items via PowerShell and CSV

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 post, we’ll create items in a SharePoint Online list using the Invoke-PnPSPRestMethod by importing a CSV file. Let’s go! 🚀

The CSV file

Nothing specific in the .csv file compared to other methods of creating items. The difference will only rely on the command parameters.

For this example, I just have three (3) columns/headers in my list:

  • Title
  • OfficeLocation
  • Country

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-NAME>)/items

Here’s what it’d look like:

$csvFile = Import-Csv -Path "<file-path.csv>"

foreach($item in $csvFile){
   $eachItem = @{
       Title = $item.Title
       OfficeLocation = $item.OfficeLocation
       Country = $item.Country
   }
   Invoke-PnPSPRestMethod -Method Post -Url "/_api/web/lists/GetByTitle('PnP List')/items" -Content $eachItem

} #end of foreach loop

Thanks for reading! 🙂

Discover more from Veronique's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading