SharePoint Online: Xuất các mục danh sách sang CSV bằng PowerShell
Yêu cầu: Xuất các mục danh sách SharePoint Online sang tệp CSV.
Làm cách nào để xuất các mục danh sách SharePoint Online sang Excel hoặc CSV?
Bạn có cần xuất dữ liệu từ danh sách SharePoint Online sang CSV không? Bạn có thể muốn xuất các mục danh sách SharePoint Online sang Excel hoặc CSV vì một số lý do. Ví dụ: bạn có thể muốn tạo bản sao lưu dữ liệu của mình. Bạn có thể cần di chuyển dữ liệu của mình sang nền tảng hoặc ứng dụng khác để phân tích hoặc thao tác thêm. Dù lý do là gì đi nữa thì Microsoft đã làm cho quá trình này trở nên khá đơn giản. Bài đăng trên blog này sẽ chỉ cho bạn cách xuất các mục danh sách SharePoint Online sang CSV bằng PowerShell và giao diện trình duyệt web. Bắt đầu nào!
Làm cách nào để xuất danh sách SharePoint sang CSV? Để xuất danh sách SharePoint Online sang Tệp CSV, chỉ cần điều hướng đến danh sách và nhấp vào “Xuất sang CSV” từ menu “Xuất” và SharePoint xuất dữ liệu danh sách sang tệp CSV. Nó đơn giản mà!
Tập lệnh PowerShell để xuất các mục danh sách SharePoint sang CSV
Mặc dù bạn có thể xuất dữ liệu danh sách sang tệp CSV theo cách thủ công, như được mô tả ở trên, nhưng bạn có thể phải tự động hóa quy trình trong một số trường hợp. Tôi sẽ chỉ cho bạn cách sử dụng PowerShell để xuất các mục danh sách SharePoint Online sang định dạng CSV.
Đây là cách bạn có thể xuất danh sách SharePoint Online sang CSV qua PowerShell:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
##Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/poc"
$ListName="Employee"
$ExportFile ="c:\Scripts\ListRpt.csv"
$UserName="Salaudeen@crescent.com"
$Password ="Password goes here"
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Context.Credentials = $credentials
#Get the List
$List = $Context.web.Lists.GetByTitle($ListName)
#Get All List Items
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$ListItems = $List.GetItems($Query)
$context.Load($ListItems)
$context.ExecuteQuery()
#Array to Hold List Items
$ListItemCollection = @()
#Fetch each list item value to export to excel
$ListItems | foreach {
$ExportItem = New-Object PSObject
$ExportItem | Add-Member -MemberType NoteProperty -name "Title" -value $_["Title"]
$ExportItem | Add-Member -MemberType NoteProperty -Name "Department" -value $_["Department"]
#Add the object with the above properties to the Array
$ListItemCollection += $ExportItem
}
#Export the result Array to CSV file
$ListItemCollection | Export-CSV $ExportFile -NoTypeInformation
Write-host "List data Exported to CSV file successfully!"
Xin lưu ý rằng tập lệnh này nhận tất cả các mục danh sách trong một danh sách nhưng không nhận đệ quy các mục của thư mục và thư mục con (Nếu bạn có thư mục và thư mục con). Để truy xuất tất cả các mục danh sách theo cách đệ quy, chỉ cần thay đổi phần truy vấn CAML thành:
#Get all List items from the library Including Items in Sub-Folder
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml="<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType'/><Value Type='Integer'>0</Value></Eq></Where></Query></View>"
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()
SharePoint Online PowerShell để xuất danh sách sang CSV
Trong khi tập lệnh trên xuất các cột đã chọn sang tệp Excel, hãy thay đổi nó để xuất tất cả dữ liệu cột sang Excel.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
##Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/"
$ListName= "Projects"
$ExportFile ="c:\ListItems.csv"
#Get Credentials to connect
$Cred = Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Ctx.Credentials = $Credentials
#Get the List
$List = $Ctx.web.Lists.GetByTitle($ListName)
#Get All List Items
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$ListItems = $List.GetItems($Query)
$FieldColl = $List.Fields
$Ctx.Load($ListItems)
$Ctx.Load($FieldColl)
$Ctx.ExecuteQuery()
#Array to Hold List Items
$ListItemCollection = @()
#Fetch each list item value to export to excel
Foreach($Item in $ListItems)
{
$ExportItem = New-Object PSObject
Foreach($Field in $FieldColl)
{
if($NULL -ne $Item[$Field.InternalName])
{
#Expand the value of Person or Lookup fields
$FieldType = $Item[$Field.InternalName].GetType().name
if (($FieldType -eq "FieldLookupValue") -or ($FieldType -eq "FieldUserValue"))
{
$FieldValue = $Item[$Field.InternalName].LookupValue
}
else
{
$FieldValue = $Item[$Field.InternalName]
}
}
$ExportItem | Add-Member -MemberType NoteProperty -name $Field.InternalName -value $FieldValue
}
#Add the object with above properties to the Array
$ListItemCollection += $ExportItem
}
#Export the result Array to CSV file
$ListItemCollection | Export-CSV $ExportFile -NoTypeInformation
Write-host "List data Exported to CSV file successfully!"
Và đầu ra:
Xuất danh sách SharePoint Online lớn hơn sang tệp CSV
Điều gì sẽ xảy ra nếu danh sách của bạn có hơn 5000 mục? Còn việc nhận các giá trị từ các trường đặc biệt như MMS, Tra cứu nhiều lần, URL, v.v. thì sao?
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/PMO"
$ListName= "Projects"
$ExportFile ="C:\temp\Projects.csv"
$BatchSize = 500
#Get Credentials to connect
$Cred = Get-Credential
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the List
$List = $Ctx.web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
#Get All List Fields
$FieldColl = $List.Fields
$Ctx.Load($FieldColl)
$Ctx.ExecuteQuery()
#Filter List fields - Skip Read only, hidden fields, content type and attachments
$ListFields = $FieldColl | Where { (-Not ($_.ReadOnlyField)) -and (-Not ($_.Hidden)) -and ($_.InternalName -ne "ContentType") -and ($_.InternalName -ne "Attachments") }
#Define Query to get List Items in batch
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml = @"
<View Scope='RecursiveAll'>
<Query>
<OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
</Query>
<RowLimit Paged="TRUE">$BatchSize</RowLimit>
</View>
"@
#Array to Hold List Items
$ListItemCollection = @()
#Get List Items in Batch
Do
{
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()
#Fetch each list item value to export to excel
Foreach($Item in $ListItems)
{
$ExportItem = New-Object PSObject
Foreach($Field in $ListFields)
{
If($NULL -ne $Item[$Field.InternalName])
{
#Handle Special Fields
$FieldType = $Field.TypeAsString
If($FieldType -eq "User" -or $FieldType -eq "UserMulti" -or $FieldType -eq "Lookup" -or $FieldType -eq "LookupMulti")
{
$FieldValue = $Item[$Field.InternalName].LookupValue -join "; "
}
ElseIf($FieldType -eq "URL") #Hyperlink
{
$URL = $Item[$Field.InternalName].URL
$Description = $Item[$Field.InternalName].Description
$FieldValue = "$URL, $Description"
}
ElseIf($FieldType -eq "TaxonomyFieldType" -or $FieldType -eq "TaxonomyFieldTypeMulti") #MMS
{
$FieldValue = $Item[$Field.InternalName].Label -join "; "
}
Else
{
#Get Source Field Value
$FieldValue = $Item[$Field.InternalName]
}
}
$ExportItem | Add-Member -MemberType NoteProperty -name $Field.InternalName -value $FieldValue
}
#Add the object with above properties to the Array
$ListItemCollection += $ExportItem
}
$Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
}
While($Query.ListItemCollectionPosition -ne $null)
#Export the result Array to CSV file
$ListItemCollection | Export-CSV $ExportFile -NoTypeInformation
Write-host "List data Exported to CSV file successfully!"
Xuất các mục danh sách SharePoint Online sang CSV bằng PnP PowerShell
Để xuất danh sách SharePoint Online sang CSV, hãy sử dụng tập lệnh PowerShell này. Tập lệnh này xuất các giá trị trường đã chọn từ danh sách đã cho. Điều đầu tiên bạn cần làm là kết nối với URL trang web SharePoint Online của bạn. Sau đó, lấy tất cả các mục danh sách từ danh sách mục tiêu mà bạn muốn xuất. Cuối cùng, Chạy lệnh ghép ngắn Xuất-CSV và chỉ định đường dẫn mà bạn muốn xuất dữ liệu danh sách SharePoint sang tệp CSV. Lệnh ghép ngắn Xuất-Csv cũng có các tham số hữu ích khác như Nối, Mã hóa, v.v.
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/projects"
$ListName = "Projects"
$SelectedFields = @("ProjectName","Project_x0020_Manager", "StartDate")
$CSVPath = "C:\Temp\ListData.csv"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get List items from the list
$ListItems = Get-PnPListItem -List $ListName -Fields $SelectedFields -PageSize 500
#Iterate through each item and extract data
$ListDataColl = @()
$ListItems | ForEach-Object {
$ListData = New-Object PSObject
#Get the Field Values of the item as text
$ListItem = Get-PnPProperty -ClientObject $_ -Property FieldValuesAsText
ForEach($Field in $SelectedFields)
{
$ListData | Add-Member Noteproperty $Field $ListItem[$Field]
}
$ListDataColl += $ListData
}
#Export data to CSV
$ListDataColl
$ListDataColl | Export-CSV $CSVPath -NoTypeInformation
Thao tác này sẽ xuất tất cả các mục danh sách từ danh sách được chỉ định sang tệp CSV có tên “ListData.csv” trong thư mục “C:\Temp” trên máy tính của bạn. Sau đó, bạn có thể mở tệp này trong Excel hoặc chương trình bảng tính khác để xem dữ liệu. Đảm bảo bạn đã cài đặt mô-đun PnP PowerShell trước khi chạy tập lệnh này.
Làm cách nào để xuất tất cả các giá trị trường có sẵn từ danh sách SharePoint Online? Chà, đây là PnP PowerShell để xuất các mục danh sách trực tuyến SharePoint sang CSV:
#Config Parameter
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Access Requests"
$CSVPath = "C:\Temp\ListData.csv"
$ListDataCollection= @()
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
$Counter = 0
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000
#Get all items from list
$ListItems | ForEach-Object {
$ListItem = Get-PnPProperty -ClientObject $_ -Property FieldValuesAsText
$ListRow = New-Object PSObject
$Counter++
Get-PnPField -List $ListName | ForEach-Object {
$ListRow | Add-Member -MemberType NoteProperty -name $_.InternalName -Value $ListItem[$_.InternalName]
}
Write-Progress -PercentComplete ($Counter / $($ListItems.Count) * 100) -Activity "Exporting List Items..." -Status "Exporting Item $Counter of $($ListItems.Count)"
$ListDataCollection += $ListRow
}
#Export the result Array to CSV file
$ListDataCollection | Export-CSV $CSVPath -NoTypeInformation -Encoding UTF8
Tập lệnh này lấy tất cả các mục trong danh sách và xuất chúng sang tệp CSV. Nếu bạn muốn áp dụng bộ lọc cho các mục danh sách, Giả sử bạn muốn nhận tất cả các mục danh sách được tạo trong 30 ngày qua, bạn có thể sử dụng:
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 | ? { $_["Created"] -gt (Get-Date).AddDays(-30) }
Bài viết liên quan:
- SharePoint Online: Báo cáo nhóm và người dùng trang web bằng PowerShell
- Xuất các mục danh sách sang CSV trong SharePoint Server bằng PowerShell
- SharePoint Online: Xóa hàng loạt tệp khỏi CSV bằng PowerShell


