Introduction

In this blog, you will learn how to export SharePoint Online list items to a CSV using PnP PowerShell.
Prerequisites
Ensure SharePoint PnP PowerShell Online cmdlets are installed. Click here for more details on how to install.
Steps Involved
Open Notepad.
Copy the below code and save the file as ExportList.ps1.
  1. ###### Declare and Initialize Variables ######
  2. $url="https://c986.sharepoint.com/sites/vijai"
  3. $listName="Test List"
  4. $currentTime= $(get-date).ToString("yyyyMMddHHmmss")
  5. $logFilePath=".\log-"+$currentTime+".docx"
  6. # Fields that has to be retrieved
  7. $Global:selectProperties=@("Title","Comments","Status");
  8. ## Start the Transcript
  9. Start-Transcript -Path $logFilePath
  10. ## Export List to CSV ##
  11. function ExportList
  12. {
  13. try
  14. {
  15. # Get all list items using PnP cmdlet
  16. $listItems=(Get-PnPListItem -List $listName -Fields $Global:selectProperties).FieldValues
  17. $outputFilePath=".\results-"+$currentTime+".csv"
  18. $hashTable=@()
  19. # Loop through the list items
  20. foreach($listItem in $listItems)
  21. {
  22. $obj=New-Object PSObject
  23. $listItem.GetEnumerator() | Where-Object { $_.Key -in $Global:selectProperties }| ForEach-Object{ $obj | Add-Member Noteproperty $_.Key $_.Value}
  24. $hashTable+=$obj;
  25. $obj=$null;
  26. }
  27. $hashtable | export-csv $outputFilePath -NoTypeInformation
  28. }
  29. catch [Exception]
  30. {
  31. $ErrorMessage = $_.Exception.Message
  32. Write-Host "Error: $ErrorMessage" -ForegroundColor Red
  33. }
  34. }
  35. ## Connect to SharePoint Online site
  36. Connect-PnPOnline -Url $url -UseWebLogin
  37. ## Call the Function
  38. ExportList
  39. ## Disconnect the context
  40. Disconnect-PnPOnline
  41. ## Stop Transcript
  42. Stop-Transcript
Open Windows PowerShell and navigate to the location where the file is placed.
Run the following command.
  1. .\ExportList.ps1
CSV file is generated with all the required details.
Reference
https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/get-pnplistitem?view=sharepoint-ps

Summary

Thus, in this blog, you saw how to export SharePoint Online list items to a CSV using PnP PowerShell.