Created
June 14, 2013 22:43
-
-
Save nzbart/5785856 to your computer and use it in GitHub Desktop.
Resets all permissions on a folder to a specified set. I use this on IIS web roots in deployment scripts. The function:
* Creates the folder if it does not exist
* Sets permissions on the folder and configures those permissions to propagate to child folders and files
* Resets all child objects so that they match the parent folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function CreateFolderWithPermissions($folder, $aclRules) | |
{ | |
if(-not (test-path $folder)) { | |
Write-Host "Creating $folder..." | |
md $folder | out-null | |
} | |
Write-Host "Setting permissions on $folder..." | |
$domain = [environment]::userdomainname | |
$acl = new-object System.Security.AccessControl.DirectorySecurity | |
$acl.SetAccessRuleProtection($true, $false) | |
$aclRules | % { | |
$specifiedPermissions = $_.Replace('{domain}', $domain).Split(';') | |
$permission = $specifiedPermissions[0],$specifiedPermissions[1],([System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit),'None',$specifiedPermissions[2] | |
$rule = new-object System.Security.AccessControl.FileSystemAccessRule $permission | |
$acl.SetAccessRule($rule) | |
} | |
Set-Acl $folder $acl | |
Write-Host "New permissions for ${folder}:" | |
Write-Host (Get-Acl $folder).AccessToString | |
Write-Host "Resetting permissions on all subfolders and files in $folder..." | |
dir -fo $folder | % { | |
icacls $_.FullName /reset /t /q | Out-Null | |
if(!$?) { | |
throw "Failed to set file permissions." | |
} | |
} | |
} | |
#Example usage | |
$folder = 'C:\Temp\TestFolder' | |
CreateFolderWithPermissions $folder 'Everyone;ReadAndExecute;Allow', 'Administrators;FullControl;Allow' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment