Powershell: File & Folder recursive take ownership and change permissions

File and Folder permission changes not propagating when ACLs modified by script

Some time ago I wrote a post on archiving user data following a users departure – those scripts have worked well for me so far as I invariably had requisite permissions on all files and folders.

I recently had an AD cleanup / data archive task where my scripts failed due to insufficient rights (Files owned by User, no SYSTEM or BUILTIN\Administrators permissions) – folder structure and permissions a mess that had grown and been neglected for years.

Sure – I could have gone through the GUI for each failed folder structure, taken ownership and forced permission changes recursively – but that would have been massively time consuming, I needed my scripts to make the necessary changes without intervention. Goes without saying but I’ll say it anyway (as people always do); change XYZ\GROUP to your own domain\group or account.


First attempts I tried using powershell’s get-ACL and set-ACL commands combined with Windows takeown.exe; worked at changing permissions on $Folder (variable set previously) but did not force the changes to propagate to existing child items and was generally unsatisfactory.

	takeown.exe /f $Folder /a
	$CurrentACL = Get-Acl $Folder
        takeown.exe /f $Folder /a /r /d Y

	write-host ...Adding AdminGroup to $Folder -Fore Green
	$AdminACLPermission = "BUILTIN\Administrators", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
	$SystemAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $AdminACLPermission
	$CurrentACL.AddAccessRule($SystemAccessRule)

        #repeat above 4 lines for 'NT AUTHORITY\System'

	Set-Acl -Path $Folder -AclObject $CurrentACL


 

A little research for a better method took me to the NTFSSecurity Module

A much simpler and effective method – using the Windows Powershell NTFSSecurity Module to process a list of folders read from a text file; the following script changes Owner to Admins and then processes each sub-dir and file (including hidden -force), changing owner and adding required permissions.

It’s straight-forward and self explanatory, much simpler than above method and forces the changes recursively on existing files. Note it adds these permissions so existing ones are otherwise unaffected.

In their own words:
Managing permissions with PowerShell is only a bit easier than in VBS or the command line as there are no cmdlets for most day-to-day tasks like getting a permission report or adding permission to an item. PowerShell only offers Get-Acl and Set-Acl but everything in between getting and setting the ACL is missing. This module closes the gap.

The module can be downloaded and documentation viewed from the Technet Script Centre.


$a = Get-Content "C:\Scripts\MERC_PROF.txt"
foreach ($i in $a)
{
    if(test-path $i)
  {
        write-host Taking ownership of Directory $i -fore Green 
        get-item $i | set-owner -Account 'XYZ\Domain Admins'
        get-item $i | add-ace -account 'BUILTIN\Administrators' -AccessRights FullControl
        get-item $i | Add-Ace -Account 'NT AUTHORITY\System' -AccessRights FullControl
        get-item $i | Add-Ace -Account 'XYZ\willf' -AccessRights FullControl

        $items = @()
        $items = $null
        $path = $null
        $items = get-childitem $i -recurse -force
        foreach($item in $items)
            {
                $path = $item.FullName
                Write-Host ...Adding AdminGroup to $path -Fore Green
                Get-Item -force $path | Set-Owner -Account 'XYZ\Domain Admins'
                Get-Item -force $path | Add-Ace -Account 'BUILTIN\Administrators' -AccessRights FullControl
            }
   }
}

Download NTFSSecurity module, copy to your Powershell modules folder, unblock all the files in the folder (either through Powershell or Explorer), import-module NTFSSecurity at start of script. Enjoy…

7 comments to “Powershell: File & Folder recursive take ownership and change permissions”
  1. This script worked as I expected, but I had to change the names of some of the commands to match the version of NTFSSecurity I am using. I changed set-owner to SET-NTFSOwner and add-ace to
    Add-NTFSAccess

  2. Thank you, just saved me a few hours manually taking ownership of a hundred roaming profile folders.

  3. I’m having an issue where when the script runs I get access denied errors. For example

    get-childitem : Access to the path ‘\\we-filcl1\home$\xxxx\Pictures’ is denied.

    get-childitem : Access to the path ‘\\we-filcl1\home$\xxxx\Videos is denied.

    etc…

    It happens to all the subdirectories. Although it looks like the script runs correctly after that. Any ideas why I would get these errors

  4. Sadly doesn’t deal with “The specified path, file name, or both are too long”.

    I’d love to see a script that handles this case (e.g. by traversing the subdirs and any that are over e.g. 10 chars long, save the dir name into a variable, rename the dir, etc, until the full path is under 248 characters long)

    I’d love to see such a script, but not so much that I can be bothered to write it myself 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.