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! 🚀
👉 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. 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
👉 The Invoke-PnPSPRestMethod is inside the loop, like any other command.
Thanks for reading! 🙂