Created
March 2, 2025 16:03
-
-
Save bixb0012/9ac4c2604d5022817e9cf8e34592a374 to your computer and use it in GitHub Desktop.
PowerShell: File System ACLs
This file contains hidden or 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
#Requires -Version 5.1 | |
# Reference: 1) https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/get-acl?view=powershell-5.1 | |
$DirectoryPath = "" # Path to directory, and subdirectories, to apply changes | |
$ExistingAccountName = "" # samAccountName or UserPrincipalName of account with existing | |
# file system object ACLs | |
$NewAccountName = "" # samAccountName or UserPrincipalName of account to assign | |
# file system object ACLs | |
# Example 1: Replace existing account access with same access for new account | |
$ExistingAccount = [Security.Principal.NTAccount]$ExistingAccountName | |
$NewAccount = [Security.Principal.NTAccount]$NewAccountName | |
foreach ($Fso in (Get-ChildItem -Path $DirectoryPath -Recurse)) { | |
$Acl = Get-Acl -Path $Fso.FullName | |
$AclUpdated = $false | |
$AclError = $false | |
foreach ($Access in $Acl.Access) { | |
if ($Access.IdentityReference -eq $ExistingAccount -and $Access.IsInherited -eq $false) { | |
$NewAccess = $null | |
$NewAccess = $Acl.AccessRuleFactory( | |
$NewAccount, | |
$Access.FileSystemRights, | |
$Access.IsInherited, | |
$Access.InheritanceFlags, | |
$Access.PropagationFlags, | |
$Access.AccessControlType | |
) | |
if ($NewAccess) { | |
[void]$Acl.RemoveAccessRule($Access) | |
$Acl.AddAccessRule($NewAccess) | |
$AclUpdated = $true | |
} | |
else { | |
Write-Warning "Unable to create new access for $($Fso.FullName)" | |
$AclError = $true | |
} | |
} | |
} | |
if ($AclUpdated -and (-not $AclError)) { | |
Write-Host "Applying updated permissions: $($Fso.FullName)" | |
Set-Acl -Path $Fso.FullName -AclObject $Acl | |
Write-Host "Completed updating permissions: $($Fso.FullName)" | |
} | |
} | |
# Example 2: Replace existing account ownership with new account | |
$ExistingAccount = [Security.Principal.NTAccount]$ExistingAccountName | |
$NewAccount = [Security.Principal.NTAccount]$NewAccountName | |
foreach ($Fso in (Get-ChildItem -Path $DirectoryPath -Recurse)) { | |
$Acl = Get-Acl -Path $Fso.FullName | |
$AclUpdated = $false | |
if ($Acl.Owner -eq $ExistingAccount) { | |
$Acl.SetOwner($NewAccount) | |
$AclUpdated = $true | |
} | |
if ($AclUpdated) { | |
Write-Host "Updating ownership: $($Fso.FullName)" | |
Set-Acl -Path $Fso.FullName -AclObject $Acl | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment