Skip to content

Instantly share code, notes, and snippets.

@jstangroome
Created August 20, 2010 04:45
Show Gist options
  • Save jstangroome/539626 to your computer and use it in GitHub Desktop.
Save jstangroome/539626 to your computer and use it in GitHub Desktop.
Grant-FileSystemAccess
function Grant-FileSystemAccess (
[string]$Path,
[string]$UserName,
[System.Security.AccessControl.FileSystemRights]$Rights
) {
$Inherit = [System.Security.AccessControl.InheritanceFlags]'None'
$Propagation = [System.Security.AccessControl.PropagationFlags]'None'
if ((Get-Item -Path $Path).PSIsContainer) {
$Inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
}
$Rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $UserName, $Rights, $Inherit, $Propagation, 'Allow'
$Acl = Get-Acl -Path $Path
$ExistingRule = $Acl.Access | Where-Object {
$_.IdentityReference -eq $Rule.IdentityReference -and
$_.FileSystemRights -eq $Rule.FileSystemRights -and
$_.InheritanceFlags -eq $Rule.InheritanceFlags -and
$_.PropagationFlags -eq $Rule.PropagationFlags -and
$_.AccessControlType -eq $Rule.AccessControlType
}
if (-not $ExistingRule) {
Write-Verbose -Message "Changing ACL for $Path. $($Rule | Out-String)"
$Acl.SetAccessRule($Rule)
Set-Acl -Path $Path -AclObject $Acl
} else {
Write-Verbose -Message "ACL for $Path exists. $($ExistingRule | Out-String)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment