title: Set permission/share subfolder to group in a library with powershell
body: <p>I am using SP 2013.</p>
  
  <p>I have to set specific permissions to subfolders in a document library</p>
  
  <p>I have the following script:</p>
  
  <pre><code>Add-PSSnapin Microsoft.SharePoint.PowerShell 
  
  Function GetFiles($folder)
  { 
     # Use recursion to loop through all subfolders.
     foreach ($subFolder in $folder.SubFolders)
     {
  
         GetFiles($subFolder)
     }
  
     if($folder.Name -eq "C" -Or $folder.Name -eq "B3-B6" -Or $folder.Name -eq "C8" -Or $folder.Name -eq "D" -Or $folder.Name -eq "A5" -Or $folder.Name -eq "A1-A4")
          {
              Write-Host "+"$folder.Name
  
              if($folder.Name -eq "C8")
              {
                  $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($web.SiteGroups["HumanResources-HR - C8"])
              }
              else
              { 
                  $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($web.SiteGroups["HumanResources-HR - Other"])
              }
              #Get Permission Level, such as "Read", "Contribute", etc
  
              $roleAssignment.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
              $roleAssignment.RoleDefinitionBindings.Add($web.RoleDefinitions["Read"])
              #Grant Access to specified Group
              $folder.RoleAssignments.Add($roleAssignment)
              #To Remove Access: Call  $item.RoleAssignments.Remove($group) . No Need for objects: roleAssignment, roleDefinition
              $folder.Update();
              Write-Host "Successfully added $($PermissionLevel) to $GroupName group in $($folder.Name)" -foregroundcolor Green
          }
   }
  
      $web = Get-SPWeb -Identity "xxx.xxx.xxx/sites/xxx"
  
  
  $rfolder=$web.Lists["DOKUMENTNA KNJIŽNICA"].RootFolder
  GetFiles($rfolder)
  </code></pre>
  
  <p>and I got an error in the line: $folder.RoleAssignments.Add($roleAssignment)</p>
  
  <blockquote>
    <p>You cannot call a method on a null-valued expression. At line:29 char:13 + $folder.RoleAssignments.Add($roleAssignment) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull</p>
  </blockquote>
  
  <p>and this happens with all folders.</p>
  
  <p>I tried the same code to set permissions to the whole library and it worked. But it does not work with folders.</p>
  
  <p>Plese help me. Thank you</p>