function Set-FolderPermission
{
<#
.SYNOPSIS
Sets the permissions on the given folder.
.DESCRIPTION
The folder permissions are set such that Administrators have Full Control.
Other permissions remain intact.
.PARAMETER Path
The path of the folder whose permissions are who be set.
.EXAMPLE
Set-FolderPermission -Path 'C:\Foo\Bar'
#>
[CmdletBinding()]
param (
[Parameter()]
[string]
$Path
)
# Get a reference to the well-known SID for the local administrators group.
[Security.Principal.SecurityIdentifier]$adminsSid = [Security.Principal.SecurityIdentifier]::new(([Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid), $null)
$folderAcl = Get-Acl -Path $Path
$folderAcl.SetAccessRuleProtection($true, $true)
Set-Acl -Path $Path -AclObject $folderAcl
# Get the list of access rules from the ACL, so we can remove and modify some of them.
$folderAcl = Get-Acl -Path $Path
[Security.AccessControl.AuthorizationRuleCollection]$accessRules = $folderAcl.GetAccessRules($true, $false, [Security.Principal.SecurityIdentifier])
[bool]$aclModified = $false
for ([int]$i = 0; $i -lt $accessRules.Count; $i++)
{
# If the access rule belongs to Administrators...
if ($accessRules[$i].IdentityReference -eq $adminsSid)
{
# ... and the permissions are not Full Control, set them to Full Control.
if (([Security.AccessControl.FileSystemAccessRule]$accessRules[$i]).FileSystemRights -ne ([Security.AccessControl.FileSystemRights]::FullControl))
{
[bool]$modified = $false
[Security.AccessControl.FileSystemAccessRule]$adminsAccessRule = [Security.AccessControl.FileSystemAccessRule]::new(
$adminsSid,
[Security.AccessControl.FileSystemRights]::FullControl,
[Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit,
[Security.AccessControl.PropagationFlags]::None,
[Security.AccessControl.AccessControlType]::Allow)
[bool]$successful = $folderAcl.ModifyAccessRule([System.Security.AccessControl.AccessControlModification]::Reset, $adminsAccessRule, [ref]$modified)
$aclModified = $aclModified -or $modified
}
}
}
# If the ACL was modified in the above loop, set the ACL on the installation folder.
if ($aclModified)
{
Set-Acl -Path $Path -AclObject $folderAcl
}
}