In the earlier article, we saw, how to get the size using SSOM. But in recent times, customers are interested in CSOM rather than SSOM.
The specific reason behind this could be, if the Content DB is not properly planned/configured, the executing a SSOM Power shell Script can cause a Content DB lock. Hence, if there is a huge Content DB, then always prefer the CSOM rather than SSOM, though the SSOM is having much more performance advantages.
The same piece of SSOM code runs much faster than CSOM code. But CSOM will not lock the DBs.
Hence, the same functionality, the below code is the equivalent CSOM script. But in CSOM, we cannot find the size of each version. At least as of now I guess.
The below code will get the Size of the Documents within a document library. The size is the final version size.
cls
Import-Module 'C:SATHISHPRACTICE SOURCE CODESOffice365.ConsolepackagesMicrosoft.SharePointOnline.CSOM.16.1.6420.1200libnet45Microsoft.SharePoint.Client.dll'
Import-Module 'C:SATHISHPRACTICE SOURCE CODESOffice365.ConsolepackagesMicrosoft.SharePointOnline.CSOM.16.1.6420.1200libnet45Microsoft.SharePoint.Client.Runtime.dll'
#Mysite URL
$site = 'https://sppalsmvp.sharepoint.com/sites/DeveloperSite/'
#Admin User Principal Name
$admin = 'sathish@sppalsmvp.OnMicrosoft.Com'
#Get Password as secure String
$password = Read-Host 'Enter Password' -AsSecureString
#Get the Client Context and Bind the Site Collection
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
#Authenticate
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($admin , $password)
$context.Credentials = $credentials
$list = $context.Web.Lists.GetByTitle('D1')
$context.Load($list)
$context.ExecuteQuery()
if ($list.BaseType -eq “DocumentLibrary”)
{
$docSize=0
$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$camlQuery.ViewXml ="<View Scope='RecursiveAll' />";
$allItems=$list.GetItems($camlQuery)
$context.Load($allItems)
$context.ExecuteQuery()
foreach($item in $allItems)
{
if($item.FileSystemObjectType -eq "File")
{
$file = $item.File
$fItem = $file.ListItemAllFields
$context.Load($file)
$context.Load($fItem)
$context.ExecuteQuery()
$docSize=$fItem["File_x0020_Size"]/1048576
#Write-Host "Filename" $fItem["FileLeafRef"].Split('.')[0]
Write-Host $list.Title + ',' + $file.ServerRelativeUrl + ',' + $fItem["FileLeafRef"].Split('.')[0] + ',' + $docSize
}
}
}
Happy Coding,
Sathish Nadarajan.
Leave a comment