Home » PowerShell » PowerShell – Recursively Set Permission on Files

PowerShell – Recursively Set Permission on Files

Use the Set-Acl cmdlet in PowerShell to change the security descriptor for the file, folders, or registry key. It applies security descriptors recursively on multiple files or folders.

ACL ( Access Control List) represents the user’s and user group’s permission to access a file or registry key. It is a list of access control entries (ACE).

In this article, we will discuss how to use the Set-ACL cmdlet to recursively set the permission on files or any resource.

Use Set-ACL to Apply Security Descriptor to Multiple Files

Use the Get-ACL command to get the security descriptors for the file and use the Set-ACL in PowerShell to recursively apply security descriptors to files.

# Get the security descriptor for the file using Get-ACL
$newACL = Get-ACL D:\exported_ua.cer

# Use the Get-ChildItem to recusively to apply security descriptor using set-acl
Get-ChildItem -Path "D:\Certificates" -Recurse -Include "*.cer" -Force | Set-Acl -AclObject $newAcl

In the above PowerShell script, the Get-ACL cmdlet in PowerShell gets the security descriptors and stores them in the $newACL variable.

The Get-ChildItem command uses the Path parameter to specify the directory path and uses the Recurse parameter to recursively look for files in all subdirectories having .cer file extension.

It passes one or more retrieved files to the Set-ACL cmdlet which applies the security descriptor in the AclObject parameter to all files recursively.

Cool Tip: How to unblock files using PowerShell!

PowerShell Set Permission on Folders and Files Recursively using Set-ACL

Use the Set-ACL cmdlet to change or apply security descriptors to folders and files recursively.

# Get the security descriptor for the folder
$newACL = Get-ACL -Path 'D:\Certificates\'

# Create the new rule
$fileSystemRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","Allow")   

# Set the new rule
$newACL.SetAccessRule($fileSystemRule)

# Apply permission on folder recursively
Set-Acl -Path 'D:\Expiry_Certificates\' -AclObject $newACL 

In the above PowerShell script, the Get-ACL cmdlet gets the security descriptor for the folder and stores them in the $newACL.

$fileSystemRule variable contains the permission rules like “BUILTIN\Administrators”, Full Control, and Allow.

Using the SetAccessRule() method adds the new access rules to the existing $newACL.

The Set-Acl command takes the folder path and set the permission recursively on files and folders.

Cool Tip: How to get permissions on folder and subfolder in PowerShell!

Conclusion

I hope the above article on how to use the Set-ACL cmdlet in PowerShell to set the permissions on files and folders recursively is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.