Wednesday, 21 June 2017

Get All List Items in Library using PowerShell with CSOM

In this article, I am going write a simple Powershell script using client object model (CSOM) to find and retrieve all files from a document library in SharePoint Online. To use csom in Powershell, we need to load the required Microsoft SharePoint Online SDK assembly files.

The below Powershell script simply load and list all the files from given document library in a SharePoint Online site. You need to replace sharepoint site url, list name and required admin credentials with your own details.
#Add required references to SharePoint client assembly to use CSOM 
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")  
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
 
$siteUrl="https://spotenant.sharepoint.com/sites/testsite"
$UserName = "admin@spotenant.onmicrosoft.com"
$SecPwd = $(ConvertTo-SecureString 'adminPassword' -asplaintext -force) 
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$SecPwd) 
$ctx.credentials = $credentials
$ctx.Load($ctx.Web)
$ctx.ExecuteQuery()
$list=$ctx.Web.Lists.GetByTitle("Documents")
$ctx.Load($list)
$ctx.ExecuteQuery()
$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$camlQuery.ViewXml ="<View Scope='RecursiveAll' />";
$allItems=$list.GetItems($camlQuery)
$ctx.Load($allItems)
$ctx.ExecuteQuery()

foreach($item in $allItems)
{
Write-Host "##############"
Write-Host $item["FileRef"]
$file = $ctx.Web.GetFileByServerRelativeUrl($item["FileRef"]);
$ctx.Load($file)
$ctx.Load($file.ListItemAllFields)
$Author=$file.Author
$CheckedOutByUser=$file.CheckedOutByUser     
$ModifiedBy=$file.ModifiedBy
$ctx.Load($Author)
$ctx.Load($CheckedOutByUser)
$ctx.Load($ModifiedBy)
try
{
$ctx.ExecuteQuery()
Write-Host "File:" $file.Name 
Write-Host "Author:" $Author.LoginName
Write-Host "ModifiedBy:" $ModifiedBy.LoginName
if($CheckedOutByUser.LoginName -ne $null){
Write-Host "CheckedOutBy:" $CheckedOutByUser.LoginName
}}
catch{}
Write-Host "##############"
Write-Host ""
}
Along with file name and file relative url, the above script also retrieves useful information such as Author name of the file, modified username and if the file was checked out, it also returns the name of the user who currently checked-out the file and yet to checked-in.

Advertisements
Advertisements

No comments:

Post a Comment