I got the following question from a reader the other day:
I've been trying to figure out how to change permissions on a folder in PowerShell. I've looked at the Get-Acl and Set-Acl, but I can only use them to copy the settings from a pre-existing object. How do I manually configure permissions?
This is actually a quite common question, so I thought I'd write a quick post on the subject.
Get-Acl and Set-Acl
To quote the PowerShell documentation "Get-Acl gets the security descriptor for a resource, such as a file or registry key." while "Set-Acl changes the security descriptor of a specified resource, such as a file or a registry key." In other words; if you want Folder_A to have the exact same permissions as Folder_B, then you simply copy the Access Control List (ACL) of Folder_B and "paste" it onto Folder_A.
$Acl = Get-Acl "C:\Folder_B" Set-Acl "C:\Folder_A" $Acl
So far, so good.
Changing the ACL
Okay, so you want to change the ACL. Here's some sample code for how to do that:
New-Item -type directory -path C:\MyFolder $Acl = Get-Acl "C:\MyFolder" $Ar = New-Object system.security.accesscontrol.filesystemaccessrule("username","FullControl","Allow") $Acl.SetAccessRule($Ar) Set-Acl "C:\MyFolder" $Acl
So, first we create a new folder. We then copy the ACL of that folder. We then create a new AccessRule that gives "username" full control. We then add this AccessRule to the ACL, and finally we reapply the new, altered ACL to the folder.
If we wanted to we could also have used $Acl.RemoveAccessRule($Ar) or possibly $Acl.RemoveAccessRuleAll() as well.