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 try to retrieve its properties!

Solution:

The “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 occurs when you try to access an object in SharePoint Online before it has been loaded and executed. This can happen when you try to access a collection of objects, such as a list of items, before it has been requested from the server. To fix this error, you need to explicitly request the collection and then execute the query to load the data.

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://Crescent.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 Lines # 19 and 20, you will end up with the error The collection has not been initialized! Let’s take another example to retrieve all list names from a SharePoint Online site:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Projects"
 
#Setup 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 all List names from the site
$Lists = $Ctx.web.Lists
ForEach($List in $Lists)
{
    Write-host $List.Title
}

The above script fails with an error message:

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.
At C:\Users\Salaudeen\Documents\PowerShell\Get-Lists.ps1:15 char:9
+ ForEach($List in $Lists)
+ ~~~~~
+ CategoryInfo : OperationStopped: (:) [], CollectionNotInitializedException
+ FullyQualifiedErrorId : Microsoft.SharePoint.Client.CollectionNotInitializedException

Here, in this case, we should load the Lists collection first. So, to fix the issue, use the following:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Projects"
 
#Setup 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 all List names from the site
$Lists = $Ctx.web.Lists
$Ctx.Load($Lists)
$Ctx.ExecuteQuery()

ForEach($List in $Lists)
{
    Write-host $List.Title
}

So, make sure collection objects are loaded and executed before accessing them inside the loop!

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

4 thoughts on “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

  • This error also manifests itself when executing set-pnplistitem, but only within a script, running at the command line it will always complete without an error. As per the following:
    Set-PnPListItem -List $ListName -Identity $RequestID -Values @{“ProvisioningStatus”= $Status}

    The solution is to define a variable which captures the output from the set-pnplistitem cmdlet, e.g.
    $result = Set-PnPListItem -List $ListName -Identity $RequestID -Values @{“ProvisioningStatus”= $Status}

    I amended my script as above and it stopped throwing the error.

    Thanks to contributors to this GitHub issue, https://github.com/pnp/PnP-PowerShell/issues/1005, for sharing that solution.

    Reply
  • Hello there,

    I am getting this error:

    An error occurred while enumerating through a collection: 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..
    At line:1 char:1
    + $Folder.Files
    + ~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (Microsoft.Share…nt.Client.File]:d__0) [], RuntimeException
    + FullyQualifiedErrorId : BadEnumeration

    I cannot for the life of me seem to get the collection to initialize. Can you help? Code here:

    Function Get-FilesFromFolder()
    {
    Try
    {

    #Load credentials of the admin account that has access to the library
    $Cred = Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName, $Cred.Password)

    #Building Context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    #Get the library
    $Library = $Ctx.Web.Lists.GetByTitle($LibraryName)
    $Folders = $Library.RootFolder.Folders
    $Ctx.Load($Folders)
    $Ctx.ExecuteQuery()

    #Get the folder by name
    $Folder = $Folders | Where {$_.Name -eq $FolderName}
    $Ctx.Load($Folder)
    $Ctx.ExecuteQuery()

    #Iterate through each file
    Foreach($File in $Folder.Files)
    {
    #Write out each file name
    Write-Host “Now printing names for files in the folder.”
    Write-Host “There are “$Folder.ItemCount” files in the folder.”
    Write-Host -f Green $File.Name
    }
    }
    Catch
    {
    Write-Host -f Red “Error getting files.” $_.Exception.Message
    }

    }

    Reply
  • Hi. I am having an issue where the $ctx.Web collection is not initialised and try as I might, I cannot find a way to intialise/load it. Any ideas?

    Reply
    • Try loading the web object. E.g.

      #Get the web object
      $Web = $Ctx.Web
      $Ctx.Load($Ctx.Web)
      $Ctx.ExecuteQuery()
      
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *