Techibee.com

Grant FullControl Permission to User/Group on File/Folder using Powershell

In today’s article, let us see how to grant NTFS full permissions to a user account on list of files using PowerShell.

We know that permissions of a file or folder can be read using the Get-ACL cmdlets. When ran against a file/folder it lists the permissions like below.

Tip : You might have noticed that I am selecting AccessToString property to display the permissions in a readable manner. If you try to select the Access property alone, it will return the ACL object which doesn’t make sense unless you interpret them.

If we want to grant a new user(assume AD\Testuser1) to permissions of the file with FullControl, then first we have a create a ACL that we want to add.

$rule=new-object System.Security.AccessControl.FileSystemAccessRule ("mydomain\testuser1","FullControl","Allow")

It is as simple as above command. You can play with changing Username and type of permissions to customize your ACL. Once your acl is ready, then you need to read what the existing ACL of the file is. You can do that using simple Get-ACL cmdlets like below

$acl = Get-ACL c:\local\me.txt

Once we have the ACL list of the file, it is the time to update it with the new ACL entry we created. It can be done calling SetAccessRule function as specified below.

$acl.SetAccessRule($rule)

Now we the ACL list updated and we should apply the new ACL to the file. It can be done with Set-ACL cmdlets.

Set-ACL -Path C:\local\me.txt -AclObject $acl

Below is the nice PS function built with the help of above code to add any given user/group to security permissions of a file/folder.

function Grant-userFullRights {            
 [cmdletbinding()]            
 param(            
 [Parameter(Mandatory=$true)]            
 [string[]]$Files,            
 [Parameter(Mandatory=$true)]            
 [string]$UserName            
 )            
 $rule=new-object System.Security.AccessControl.FileSystemAccessRule ($UserName,"FullControl","Allow")            

 foreach($File in $Files) {            
  if(Test-Path $File) {            
   try {            
    $acl = Get-ACL -Path $File -ErrorAction stop            
    $acl.SetAccessRule($rule)            
    Set-ACL -Path $File -ACLObject $acl -ErrorAction stop            
    Write-Host "Successfully set permissions on $File"            
   } catch {            
    Write-Warning "$File : Failed to set perms. Details : $_"            
    Continue            
   }            
  } else {            
   Write-Warning "$File : No such file found"            
   Continue            
  }            
 }            
}

Output:

In the above output I have added a local account (SITARAM\Administrator) to the permissions of c:\local\me.txt file

Hope this helps and happy reading.

Exit mobile version