How to reset file or folder permissions with Powershell

How to reset file or folder permissions with Powershell

Sometimes you have to face situations where users have manually added additional permissions on files or folders and/or removed inheritance.
And now all you want is to make everything clean again by having the same permissions everywhere from the top of the tree to the last leaf.

My favorite tool

Though you can achieve all this with native PowerShell methods and a little scripting,
I prefer to use the very good module of Raimund Andree named NTFSSecurity.

The latest version is available on PowerShell Gallery here.

Don’t forget hidden files and folders

For all following actions, we will enumerate a list of files and folders with the Get-ChildItem cmdlet before piping them to other cmdlets.
Be sure to not forget sub-objects by using the Recurse parameter.
Ensure also to include all hidden objects with the Force parameter.

Restore the canonical format

Sometimes, when you try to update permissions you get the following error message:

This access control list is not in canonical form and therefore cannot be modified

Fortunately, there is an easy way to fix this behavior:
simply overwrite the current permissions with the already existing one.

Get-ChildItem -Path C:\Temp -Recurse -Force | ForEach-Object -Process {$ACL = Get-Acl -Path $PSItem.FullName; Set-Acl -Path $PSItem.FullName -AclObject $ACL}

Take ownership of the whole tree

In the following example, the Administrator account is set as the owner of all objects and sub-objects

Get-ChildItem -Path C:\Temp -Recurse -Force | Set-NTFSOwner -Account 'Administrator'

Remove manually added permissions

In the following example, all manually added (i.e. noninherited) permissions are removed.

Get-ChildItem -Path C:\Temp -Recurse -Force | Clear-NTFSAccess

Restore inheritance

In the following example, inheritance will be set on all objects.

Get-ChildItem -Path C:\Temp -Recurse -Force | Enable-NTFSAccessInheritance

Wrapping up

And if you want to do all this together, your script could look like this:

Get-ChildItem -Path 'C:\Temp' -Recurse -Force |
    ForEach-Object -Process {
        $ACL = Get-Acl -Path $PSItem.FullName
        Set-Acl -Path $PSItem.FullName -AclObject $ACL

        Set-NTFSOwner -Account 'Administrator' -Path $PSItem.FullName

        Clear-NTFSAccess -Path $PSItem.FullName

        Enable-NTFSAccessInheritance -Path $PSItem.FullName

Et voilà!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s