param(
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory=$false)]
[string]$Identity,
[switch]$CurrentUser
)
$adminRole = [Security.Principal.WindowsBuiltInRole] "Administrator"
$currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not ([Security.Principal.WindowsPrincipal]$currentIdentity).IsInRole($adminRole)) {
throw 'You do not have Administrator rights'
}
if($CurrentUser) {
$Identity = $currentIdentity.Name
} elseif([string]::IsNullOrEmpty($Identity)) {
throw 'No Identity parm provided'
}
try {
Write-Verbose "[SET ACL: $Identity] $Path"
# Take ownership
$acl = Get-Acl $Path
$owner = [System.Security.Principal.NTAccount]::new($Identity)
$acl.SetOwner($owner)
Set-Acl -Path $Path -AclObject $acl -ErrorAction Stop
# Set permissions
$acl = Get-Acl $Path
if(Test-Path -Path $Path -PathType Container) {
$accessRule = [System.Security.AccessControl.FileSystemAccessRule]::new(
$Identity,
"FullControl",
"ContainerInherit,ObjectInherit",
"None",
"Allow"
)
} else {
$accessRule = [System.Security.AccessControl.FileSystemAccessRule]::new(
$Identity,
"FullControl",
"None",
"None",
"Allow"
)
}
$acl.SetAccessRule($accessRule)
Set-Acl -Path $Path -AclObject $acl -ErrorAction Stop
}
catch {
Write-Warning $_
}
# Process subdirectories and files if it's a directory
if(Test-Path -Path $Path -PathType Container) {
try {
Get-ChildItem $Path -Force -ErrorAction Stop | ForEach-Object {
Set-OwnershipAndPermissions -Path $_.FullName -Identity $Identity
}
}
catch {
Write-Warning "Failed to access contents of $Path"
}
}