Apply rights to directory structure using PowerShell

12 09 2011

Unfortunately PowerShell doesn’t provide an Unix type command where you can apply rights to all directories and files using something similar to chmod.  What my client needed was a script to traverse a directory tree granting an AD group read only rights to each folder without granting any inheritance.  This script can easily be modified to fit your inheritance/propagation scenarios and I’ve provided a link to the .Net FileSystemAccessRule class where you can configure your security descriptors and then apply them via set-acl.

Here is a link that helped me with 99% of the script.

http://blog.netnerds.net/2007/07/powershell-set-acl-does-not-appear-to-work/

Here is a link that the previous link references with better descriptions of the security descriptors.

http://developers.de/blogs/damir_dobric/archive/2007/06/18/directory-security-and-access-rules.aspx

Here is a Microsoft article showing you how to work with security descriptors and is very useful.

http://technet.microsoft.com/en-us/library/ff730951.aspx

Here is my script:

#######################################################################################
## This script will give an AD group Read Only access to every folder in a directory
## structure
## The script will not apply inheritance
##
## Writen by Brady Randolph of RBA Consulting
########################################################################################

$path = ‘UNC Path to Folder Structure’
$path
$Folders = Get-ChildItem -Path $path -Recurse | ? {$_.mode -like "d*"} | Select-Object FullName
$Total = $Folders.Count; $Now = Get-Date; Write-Host "$Now $Total directories in $path"
foreach ($directory in $Folders) {
$directory = $directory.FullName
$Now = Get-Date; Write-Host "$Now Setting rights on $directory"
$acl = Get-Acl $directory
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule("domain\security group", "Read", $inherit, $propagation, "Allow")
$acl.AddAccessRule($accessrule)
set-acl -aclobject $acl -Path $directory -ErrorAction Continue -ErrorVariable ACLError
    if ($ACLError){
        $Now = Get-Date; Write-Host "$Now There was an error setting rights to $directory"
        $Now = Get-Date; Write-Host "$Now $ACLError"
    }
}


Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: