SharePoint 解決方案:如何獲取Library或者List下的Item數量

51CTO 博客地址:https://blog.51cto.com/13969817
博客園博客地址:https://www.cnblogs.com/bxapollo

今天給大家分享一下如何使用PowerShell CSOM 腳本爲特定的Library或者List獲取Item count,包括其下所有的文件夾中的item,這樣有利於做數據分析和統計,比如組織結構變更,需要將數據做遷移,那麼就可以通過該種方法對比遷移前的數據量和遷移後的目的端item count,以確保數據遷移前後的數量是一致的。

獲取Item count方案有很多,比如PnP PowerShell等等,本文將爲大家介紹的是PowerShell CSOM 腳本的解決方案。

具體執行分爲以下3個步驟:

  • 加載SharePoint CSOM Assemblies
  • 處理變量,確保連接SharePoint Online
  • 自定義函數從特定的網站URL的List中獲取Item數量

加載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"

但由於我環境的.net是4.0的,默認的情況下,禁用從遠程位置加載的程序集中執行代碼的功能,所以需要使用[System.Reflection.Assembly]::LoadFrom()來加載Microsoft.SharePoint.Client.dll",如下所示:

SharePoint 解決方案:如何獲取Library或者List下的Item數量

說明:加載這兩個dll文件,需要在部署SharePoint Server端執行,否則默認情況下物理路徑是沒有該文件的。

處理變量,確保連接SharePoint Online

$SiteUrl = "https://mvptrainingcn.sharepoint.com/sites/Demo2"
$ListName="TrainingDocument"
SharePoint 解決方案:如何獲取Library或者List下的Item數量

說明:需要輸入Microsoft 365 Global Admin的賬戶和密碼,如下所示:br/>$UserName="[email protected]"
$Password ="XXXXXX"
SharePoint 解決方案:如何獲取Library或者List下的Item數量

自定義函數從特定的網站URL的List中獲取Item數量

#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)
#sharepoint online get list items powershell
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$Context.Load($ListItems)
$Context.ExecuteQuery()      
write-host "Total Number of List Items found:"$ListItems.Count

SharePoint 解決方案:如何獲取Library或者List下的Item數量

可以看到獲取到的Item數量是2,與SharePoint Online的實際情況吻合,如下圖所示:

SharePoint 解決方案:如何獲取Library或者List下的Item數量

希望本次分享的數據統計方法對大家有幫助,持續關注我,後續會分享更多使用小技巧,謝謝閱讀。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章