No data returned sharepoint powershell

Vaibhav Ganesh Kaulkar 1 Reputation point
2022-05-31T10:29:23.587+00:00

Dear community experts, I am trying to break permissions for some files and then apply group permissions.

I get exception as

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

  • $listitems
  • ~~~~~~~~~~
  • CategoryInfo : InvalidOperation: (Microsoft.Share...lient.ListI
    tem]:<GetEnumerator>d__3) [], RuntimeException
  • FullyQualifiedErrorId : BadEnumeration #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" #Config Parameters $SiteURL= "" $LibraryName = "" $UserName="" $Password ="" cls #Setup Credentials to connect $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force)) #Set up the context $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) $Ctx.Credentials = $Cred #Group Name $GroupName="RestrictedGroup_Repository_CAs" #Get Credentials to connect #$Cred = Get-Credential Try {
      #Get the Library
      $List = $Ctx.web.Lists.GetByTitle($LibraryName)
    
      #Query to Get all files begins with CA adn CA_ in all Folders from the library Repository.
      $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
      $Query.ViewXml="
          <View Scope='RecursiveAll'>
              <Query>
                   <Where>                
                       <BeginsWith>
                              <FieldRef Name='LinkFilename'/>
                              <Value Type='file'>CA</Value>
    
                       </BeginsWith>  
                        <BeginsWith>
                              <FieldRef Name='LinkFilename'/>                        
                              <Value Type='file'>CA_</Value>
                       </BeginsWith>
                       <BeginsWith>
                              <FieldRef Name='LinkFilename'/>                        
                              <Value Type='file'>Confidentiality Agreements</Value>
                       </BeginsWith>              
                  </Where>
               </Query>
          </View>"
    
      $ListItems = $List.GetItems($Query)
      $Ctx.Load($ListItems)
      $Ctx.ExecuteQuery()
    
      Write-host "Total Number of CA and CA_ files in Repository library:" $ListItems.count
    
      #Loop through each file in the library
      Foreach($Item in $ListItems)
      { 
    
    
         write-host "Permission for the list item " -fore yellow
    
         #Get the Folder Item
         $Ctx.Load($Item.Folder)
         $Ctx.ExecuteQuery()
         Write-host -f Green $Item.Folder.ServerRelativeUrl
    
    
          #Get the Folder Item
          $Group =$Ctx.web.SiteGroups.GetByName($GroupName)
          $Item.Folder.BreakRoleInheritance($true)
    
    
          if ($Group -eq $null)
              {
                  $User = $Ctx.web.EnsureUser($spgroupname)
                  $Roleassign = New-Object Microsoft.SharePoint.SPRoleAssignment($User)
                 }
          else
              {
                  $Roleassign = New-Object Microsoft.SharePoint.SPRoleAssignment($Group)
                      }
                  $Roleassign.RoleDefinitionBindings.Add(($Ctx.web.RoleDefinitions | Where-Object { $_.Type -eq $permission }))
    
          $Ctx.Load($Group)
          $Ctx.ExecuteQuery()
          $Item.Folder.RoleAssignments.Add($Roleassign)
      }
    
          Write-host -f Green "Permission granted to all files starting with CA and CA_"
      }
    
    Catch { write-host -f Red "Error Getting Folder!" $_.Exception.Message }
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 40,471 Reputation points Microsoft External Staff
    2022-06-01T05:24:10.807+00:00

    Hi @Anonymous ,
    Per my test, I didn't found the error occurs. And I success BreakRoleInheritance and grant permission by following script

     #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"  
      
     #Config Parameters  
     $SiteURL = "https://xxx.sharepoint.com/sites/xiexin"  
     $LibraryName = "Document Lib"  
          
     $UserName = "******@xxx.onmicrosoft.com"  
     $Password = "aaaaaaaaaaa"  
     $PermissionLevel = "Edit"  
          
            
     #Setup Credentials to connect  
     $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))  
            
     #Set up the context  
     $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)  
     $Ctx.Credentials = $Cred  
          
     #Group Name  
     $GroupName="Read"  
            
     #Get Credentials to connect  
     #$Cred = Get-Credential  
          
     Try {  
             
         #Get the Library  
         $List = $Ctx.web.Lists.GetByTitle($LibraryName)  
           
         $Ctx.Load($List)  
         $Ctx.ExecuteQuery()  
      
         #Query to Get all files begins with CA adn CA_ in all Folders from the library Repository.  
         $Query = New-Object Microsoft.SharePoint.Client.CamlQuery  
         $Query.ViewXml="  
             <View Scope='RecursiveAll'>  
                 <Query>  
                      <Where>                  
                          <BeginsWith>  
                                 <FieldRef Name='LinkFilename'/>  
                                 <Value Type='file'>CA</Value>  
                                  
                          </BeginsWith>    
                           <BeginsWith>  
                                 <FieldRef Name='LinkFilename'/>                          
                                 <Value Type='file'>CA_</Value>  
                          </BeginsWith>  
                          <BeginsWith>  
                                 <FieldRef Name='LinkFilename'/>                          
                                 <Value Type='file'>Confidentiality Agreements</Value>  
                          </BeginsWith>                
                     </Where>  
                  </Query>  
             </View>"  
          
         $ListItems = $List.GetItems($Query)  
         $Ctx.Load($ListItems)  
         $Ctx.ExecuteQuery()  
            
         Write-host "Total Number of CA and CA_ files in Repository library:" $ListItems.count  
              
         #Loop through each file in the library  
         Foreach($Item in $ListItems)  
         {   
          
          
            write-host "Permission for the list item " -fore yellow  
          
            #Get the Folder Item  
            $Folder = $Item.Folder  
            $Ctx.Load($Folder)  
            $Ctx.ExecuteQuery()  
            Write-host -f Green $Folder.ServerRelativeUrl  
          
          
             #Get the Folder Item  
             $Group =$Ctx.web.SiteGroups.GetByName($GroupName)  
             $User = $Ctx.web.EnsureUser($UserName)  
             $Folder.ListItemAllFields.BreakRoleInheritance($True,$True)  
             $Ctx.Load($Group)  
             $Ctx.Load($User)  
             $Ctx.ExecuteQuery()  
      
             $Role = $web.RoleDefinitions.GetByName($PermissionLevel)  
             $RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)  
             $RoleDB.Add($Role)  
                
      
                
             #add sharepoint online group to folder using powershell  
             $GroupPermissions = $Folder.ListItemAllFields.RoleAssignments.Add($Group,$RoleDB)  
       
             #powershell add user to sharepoint online folder  
             $UserPermissions = $Folder.ListItemAllFields.RoleAssignments.Add($User,$RoleDB)  
             $Folder.Update()  
             $Ctx.ExecuteQuery()  
      
      
         }  
          
             Write-host -f Green "Permission granted to all files starting with CA and CA_"  
         } Catch {  
         write-host -f Red "Error Getting Folder!" $_.Exception.Message  
     }  
          
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.