Remove NTFS permissions of a user in all subdirectories

13.4k views Asked by At

I am writing a script which would delete a specific user if the account is older than 7 days.
But when the user is deleted the NTFS permissions on my file server remain.
How can I delete all the permission for a specific user with PowerShell?

1

There are 1 answers

0
Ansgar Wiechers On BEST ANSWER

You should never grant permissions to individual users (with the exception of home directories and user profiles). As you can see for yourself it's a mess to clean up. Always create groups representing the particular functions/roles that require access, and grant permissions to those groups.

You can clean up the permissions via icacls:

icacls C:\root\folder /remove DOMAIN\user /t /c

Note, however, that you MUST do this before deleting the account, because for some reason icacls can't clean up SIDs of deleted accounts.

If you have already deleted the account you can try to fix permissions with Get-Acl and Set-Acl:

Get-ChildItem C:\root\folder -Recurse -Force | ForEach-Object {
  $acl = Get-Acl -LiteralPath $_.FullName
  $ace = $acl.Access | Where-Object { $_.IdentityReference -like 'S-1-5-*' }
  $acl.RemoveAccessRule($ace) | Out-Null
  Set-Acl -LiteralPath $_.FullName -AclObject $acl
}

Note that you may need to adjust the condition for selecting the ACE to remove from the file or folder's ACL.

Note also, that the above will fail for files/folders where the owner isn't either the user running the code or one of his groups. In a situation like that you can use tools like subinacl or SetACL as a last resort, as described in the answers to this question on ServerFault.