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.
- ###### Declare and Initialize Variables ######
- $url="https://c986.sharepoint.com/sites/vijai"
- $listName="Test List"
- $currentTime= $(get-date).ToString("yyyyMMddHHmmss")
- $logFilePath=".\log-"+$currentTime+".docx"
- # Fields that has to be retrieved
- $Global:selectProperties=@("Title","Comments","Status");
-
- ## Start the Transcript
- Start-Transcript -Path $logFilePath
-
-
- ## Export List to CSV ##
- function ExportList
- {
- try
- {
- # Get all list items using PnP cmdlet
- $listItems=(Get-PnPListItem -List $listName -Fields $Global:selectProperties).FieldValues
- $outputFilePath=".\results-"+$currentTime+".csv"
-
- $hashTable=@()
-
- # Loop through the list items
- foreach($listItem in $listItems)
- {
- $obj=New-Object PSObject
- $listItem.GetEnumerator() | Where-Object { $_.Key -in $Global:selectProperties }| ForEach-Object{ $obj | Add-Member Noteproperty $_.Key $_.Value}
- $hashTable+=$obj;
- $obj=$null;
- }
-
- $hashtable | export-csv $outputFilePath -NoTypeInformation
- }
- catch [Exception]
- {
- $ErrorMessage = $_.Exception.Message
- Write-Host "Error: $ErrorMessage" -ForegroundColor Red
- }
- }
-
- ## Connect to SharePoint Online site
- Connect-PnPOnline -Url $url -UseWebLogin
-
- ## Call the Function
- ExportList
-
- ## Disconnect the context
- Disconnect-PnPOnline
-
- ## Stop Transcript
- Stop-Transcript
Open Windows PowerShell and navigate to the location where the file is placed.
Run the following command.
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.