Export SharePoint Online List Items To CSV Using PnP PowerShell

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.  
  9. ## Start the Transcript  
  10. Start-Transcript -Path $logFilePath   
  11.  
  12.  
  13. ## Export List to CSV ##  
  14. function ExportList  
  15. {  
  16.     try  
  17.     {  
  18.         # Get all list items using PnP cmdlet  
  19.         $listItems=(Get-PnPListItem -List $listName -Fields $Global:selectProperties).FieldValues  
  20.         $outputFilePath=".\results-"+$currentTime+".csv"  
  21.   
  22.         $hashTable=@()  
  23.  
  24.         # Loop through the list items  
  25.         foreach($listItem in $listItems)  
  26.         {  
  27.             $obj=New-Object PSObject              
  28.             $listItem.GetEnumerator() | Where-Object { $_.Key -in $Global:selectProperties }| ForEach-Object{ $obj | Add-Member Noteproperty $_.Key $_.Value}  
  29.             $hashTable+=$obj;  
  30.             $obj=$null;  
  31.         }  
  32.   
  33.         $hashtable | export-csv $outputFilePath -NoTypeInformation  
  34.      }  
  35.      catch [Exception]  
  36.      {  
  37.         $ErrorMessage = $_.Exception.Message         
  38.         Write-Host "Error: $ErrorMessage" -ForegroundColor Red          
  39.      }  
  40. }  
  41.  
  42. ## Connect to SharePoint Online site  
  43. Connect-PnPOnline -Url $url -UseWebLogin  
  44.  
  45. ## Call the Function  
  46. ExportList  
  47.  
  48. ## Disconnect the context  
  49. Disconnect-PnPOnline  
  50.  
  51. ## Stop Transcript  
  52. 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.