3

I am rather new to this place but quite few previous posts helped me out a great deal while creating some PowerShell scripts. I have been trying to create a script that will create a couple of folders into my document library in my SharePoint Online site. I managed to make it create the folders and break the role inheritance with existing permissions wiped after creation. Although I am struggling to make it add the permissions as I end up receiving an error.

The error is as follows:

format-default : 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. + CategoryInfo : NotSpecified: (:) [format-default], CollectionNotInitializedException + FullyQualifiedErrorId : Microsoft.SharePoint.Client.CollectionNotInitializedException,Microsoft.PowerShell.Commands.FormatDefau ltCommand

I have read a couple of other posts saying that this error means that the specific collections are not loaded but as far as I can see I have loaded in everything I can to the $ClientContext. Any help finding this collection not initialized is greatly appreciated! Find the code below.

### Get the user credentials
$credential=Get-Credential
$username=$credential.UserName
$password=$credential.GetNetworkCredential().Password
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

### Input Parameters
$url = 'https://aareSharePoint.sharepoint.com/sites/muhsite/'
$usrName = 'Aare Test'
$email = '[email protected]'

### References
# Specified the paths where the dll's are located.
Add-Type -Path 'c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'


### CreateFolder Function
function CreateFolder()
{
    # Connect to SharePoint Online and get ClientContext object.
    $clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
    $clientContext.Credentials = $credentials

    # Get the SharePoint web
    $web=$clientContext.Web;
    $clientContext.Load($web)
    $clientContext.ExecuteQuery()

    # Adds the folder that is located at the specified URL to the collection
    $folder1=$web.Folders.Add('Library1/'+$usrName)
    $folder2=$web.Folders.Add('Library2/'+$usrName)
    $clientContext.Load($folder1)
    $clientContext.Load($folder2)
    $clientContext.ExecuteQuery()

    #Get the role required and load it 
    $role = $web.RoleDefinitions.GetByName('Edit')
    $usrRole = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($clientContext)
    $usrRole.Add($role)
    $clientContext.Load($role)
    $clientContext.Load($usrRole)

    #Get the user from the $web
    $usr = $Web.EnsureUser('i:0#.f|membership|'+$email)
    Write-Host $usrRole.Description
    $clientContext.Load($usr)
    $clientContext.ExecuteQuery()

    # Display the folder name and URL
    Write-Host -ForegroundColor Green 'Folder Name: ' $folder1.Name ' URL: '$folder1.ServerRelativeUrl;
    Write-Host -ForegroundColor Green 'Folder Name: ' $folder2.Name ' URL: '$folder2.ServerRelativeUrl;

    #Break inheritance and remove existing permissions
    $folder1.ListItemAllFields.BreakRoleInheritance($false, $true)
    $folder2.ListItemAllFields.BreakRoleInheritance($false, $true)

    #Add permissions to the folders
    $folder1.ListItemAllFields.RoleAssignments.Add($usr,$usrRole)
    $folder2.ListItemAllFields.RoleAssignments.Add($usr,$usrRole)
    $clientContext.Load($folder1)
    $clientContext.Load($folder2)
    $clientContext.ExecuteQuery()


}
#Execute the function
CreateFolder

2 Answers 2

3

I tested your script and found the problem. The answer is here https://stackoverflow.com/questions/35225511/sharepoint-csom-copy-roleassignment

your last lines should be:

# Apply the permission roles to the list.
$clientContext.Load($folder1.ListItemAllFields.RoleAssignments.Add($usr, $usrRole))
$clientContext.Load($folder2.ListItemAllFields.RoleAssignments.Add($usr, $usrRole))
$folder1.Update()
$folder2.Update()
$clientContext.ExecuteQuery()
3

I have also now fixed the error which the script had that was unrelated to the question and this script should now work as intended.

### Get the user credentials
$credential = Get-Credential
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

### Input Parameters
$url = 'https://aareSharePoint.sharepoint.com/sites/muhsite/'
$usrName = 'Aare Test'
$email = '[email protected]'

### References
# Specified the paths where the dll's are located.
Add-Type -Path 'c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'


### CreateFolder Function
function CreateFolder()
{

    # Connect to SharePoint Online and get ClientContext object.
    $clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
    $clientContext.Credentials = $credentials

    Function GetRole
    {
        [CmdletBinding()]
        param
        (
            [Parameter(Mandatory = $true, Position = 1)]
            [Microsoft.SharePoint.Client.RoleType]$rType
        )

        $web = $clientContext.Web
        if ($web -ne $null)
        {
            $roleDefs = $web.RoleDefinitions
            $clientContext.Load($roleDefs)
            $clientContext.ExecuteQuery()
            $roleDef = $roleDefs | Where-Object { $_.RoleTypeKind -eq $rType }
            return $roleDef
        }
        return $null
    }

    # Get the SharePoint web
    $web = $clientContext.Web;
    $usrRDBC = $null
    # Adds the folder that is located at the specified URL to the collection
    $folder1 = $web.Folders.Add('Library1/' + $usrName)
    $folder2 = $web.Folders.Add('Library2/' + $usrName)
    $clientContext.Load($folder1)
    $clientContext.Load($folder2)
    $clientContext.ExecuteQuery()

    #Get the role required and load it 
    Write-Host $roleType
    $roleTypeObject = [Microsoft.SharePoint.Client.RoleType]$roleType
    $roleObj = GetRole $roleTypeObject
    $usrRDBC = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($clientContext)
    $usrRDBC.Add($roleObj)
    #Get the user from the $web
    $usr = $Web.EnsureUser('i:0#.f|membership|' + $email)
    Write-Host $usrRDBC.Description

    #Break inheritance and remove existing permissions
    $folder1.ListItemAllFields.BreakRoleInheritance($false, $true)
    $folder2.ListItemAllFields.BreakRoleInheritance($false, $true)

    # Apply the permission roles to the list.
    $clientContext.Load($folder1.ListItemAllFields.RoleAssignments.Add($usr, $usrRDBC))
    $clientContext.Load($folder2.ListItemAllFields.RoleAssignments.Add($usr, $usrRDBC))
    $folder1.Update()
    $folder2.Update()
    $clientContext.ExecuteQuery()

    # Display the folder name and URL
    Write-Host -ForegroundColor Green 'Folder Name: ' $folder1.Name ' URL: '$folder1.ServerRelativeUrl;
    Write-Host -ForegroundColor Green 'Folder Name: ' $folder2.Name ' URL: '$folder2.ServerRelativeUrl;

}
#Execute the function
CreateFolder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.