SharePoint Online: Fix "The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested" Error in PowerShell

Error: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
sharepoint online powershell the collection has not been initialized

Root cause:
You must load the object before you are trying retrieve its properties!

Solution: Here is how the problem can be resolved
#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"
  
#Parameters
$SiteURL = "https://crescenttech.sharepoint.com"
$UserName = "Salaudeen@TheCrescentTech.com"
$Password = "Password goes here"
$SecurePassword= $Password | ConvertTo-SecureString -AsPlainText -Force
 
#Setup the Context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
 
#Get All Fields from the List
$List = $Ctx.Web.Lists.GetByTitle("Documents")

#Load List Fields collection
$Ctx.Load($List.Fields)
$Ctx.ExecuteQuery()

ForEach($Field in $List.Fields)
{
    Write-host $Field.Title
}
Please note, if you skip the Line # 19 and 20, you would end up with the error The collection has not been initialized!
SharePoint Online: Fix "The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested" Error in PowerShell SharePoint Online: Fix "The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested" Error in PowerShell Reviewed by Salaudeen Rajack on June 11, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.