0

I am working on assigning permission groups to the list item which is in sub site level.

the same code is working fine for top level site.but getting error at sub site level.

function SetPermissionsToDocSet
{
    param($context,$docSetobject,$groupName,$role)
    try
    {                    
        $groupObj=$context.Site.RootWeb.SiteGroups.GetByName($groupName)
        $context.Load($groupObj)
        $context.ExecuteQuery()        

        $roleObj=$context.Web.RoleDefinitions.GetByName($role)
        $roleDefBinding=New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($context)
        $roleDefBinding.Add($roleObj)

        #Assign permissions        
        $context.Load($docSetobject.RoleAssignments.Add($groupObj,$roleDefBinding))
        $docSetobject.Update()
        $context.ExecuteQuery()
    }
    catch
    {
        Write-Host $_.Exception.Message
    }
}

The above code is working fine if $context is a root site context. But I get the error if $context is sub site context:

The object is used in the context different from the one associated with the object.

I am unable to add group to subsite level list item.

Please provide solution ASAP.

  • IIRC you can get sitegroups directly from your web, try changing your first line to $groupObj=$context.Web.SiteGroups... – sasfrog Aug 17 at 22:15
0

Chances are that $docSetobject.context is not the same as $context. You cannot mix them. On top of that, you don't really need to pass $context to your functions. It's already available in your $docSetobject object. via $docSetobject.context.

Make sure you use correct context this way

function SetPermissionsToDocSet
{
    param($docSetobject, $groupName, $role) # <--- You don't need to pass $context
    try
    {   
        $context = $docSetobject.Context # <--- You can take context from your object         
        $groupObj=$context.Site.RootWeb.SiteGroups.GetByName($groupName)
        $context.Load($groupObj)
        $context.ExecuteQuery()        

        $roleObj=$context.Web.RoleDefinitions.GetByName($role)
        $roleDefBinding=New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($context)
        $roleDefBinding.Add($roleObj)

        #Assign permissions        
        $context.Load($docSetobject.RoleAssignments.Add($groupObj,$roleDefBinding))
        $docSetobject.Update()
        $context.ExecuteQuery()
    }
    catch
    {
        Write-Host $_.Exception.Message
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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