Created
August 10, 2017 12:17
-
-
Save duffney/66288f55ee71ac57d4b0102659fc4b62 to your computer and use it in GitHub Desktop.
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 Add-AclAccessRule { | |
<# | |
.SYNOPSIS | |
Adds an access rule to an existing ACL on a folder or file. | |
.DESCRIPTION | |
Use .net methods to get the current ACL of the file or folder then generates a new rule | |
to which is added to the ACL of the file system object | |
.EXAMPLE | |
$splat = @{ | |
Path = 'C:\Logs' | |
IdentityReference = 'Everyone' | |
AccessControlType = 'Allow' | |
FileSystemRights = 'Modify' | |
InheritanceFlags = 'ObjectInherit,ContainerInherit' | |
PropagationFlags = 'None' | |
} | |
Add-AclAccessRule @splat | |
#> | |
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory=$true)] | |
[ValidateNotNullOrEmpty()] | |
[string]$Path, | |
[Parameter(Mandatory=$true)] | |
[ValidateNotNullOrEmpty()] | |
[Alias('Username', 'User')] | |
[string]$IdentityReference, | |
[Parameter(Mandatory=$true)] | |
[ValidateSet('Allow','Deny')] | |
[string]$AccessControlType, | |
[Parameter(Mandatory=$true)] | |
[ValidateSet('Modify','FullControl','Read','Write','ReadAndExecute','TakeOwnership')] | |
[string]$FileSystemRights, | |
[Parameter(Mandatory=$false)] | |
[ValidateSet('ObjectInherit','ContainerInherit','None','ObjectInherit,ContainerInherit')] | |
[string]$InheritanceFlags, | |
[Parameter(Mandatory=$false)] | |
[ValidateSet('InheritOnly','None','NoPropagateInherit')] | |
[string]$PropagationFlags | |
) | |
begin { | |
$ACL = (Get-Item $Path).GetAccessControl('Access') | |
$arFileSystemRights = [System.Security.AccessControl.FileSystemRights]"$FileSystemRights" | |
$arType =[System.Security.AccessControl.AccessControlType]::$AccessControlType | |
$arUser = New-Object System.Security.Principal.NTAccount("$IdentityReference") | |
if ($InheritanceFlags) { | |
$arInheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"$InheritanceFlags" | |
} | |
if ($PropagationFlags) { | |
$arPropagationFlag = [System.Security.AccessControl.PropagationFlags]::$PropagationFlags | |
} | |
$accessRule= New-Object System.Security.AccessControl.FileSystemAccessRule ($arUser, $arFileSystemRights, $arInheritanceFlag, $arPropagationFlag, $arType) | |
Write-Verbose -Message "Access Rule [$accessRule]" | |
} | |
process { | |
$ACL.AddAccessRule($accessRule) | |
Write-Verbose -Message "Modify ACL [$ACL]" | |
try { | |
Set-ACL -Path $Path -AclObject $ACL | |
} | |
catch { | |
Write-Error "ACL failed to apply new Rule" | |
} | |
} | |
end { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment