Changing Ownership of File or Folder Using PowerShell

While working on a project recently, I needed to find an easy way to take ownership of a profile folder and its subfolders to allow our support staff to either delete the profile or be able to traverse the folder to help troubleshoot issues. Typically, one could use Explorer to find the folder and then take ownership and be done with it. But the goal was to come up with a command line solution that not only worked quickly, but didn’t miss out on a file or folder.

The brief background on this is that roaming profiles sometimes would become inaccessible to our support staff in that only the user account and System would have access to the profile folder and its sub-folders and files. Also, ownership of those objects were by the user account. This created issues with deleting accounts and troubleshooting profile related issues.

Before showing the solution that I came up with, I will run down a list of attempts which never quite met my requirements and why.

Using Takeown.exe

This was actually my initial idea as I allows for recursive actions and lets me specify to grant ownership to Builtin\Administrators. Sure it wasn’t a PowerShell approach, but it met the requirements of what I wanted to do…or so I thought.

image

The first problem is that it is slow. I kicked it off on my own profile (because it is always more fun to test on yourself than others) and found that it would take upwards of 10 minutes vs. the ~2 minute UI approach. Obviously this is an issue if I expect to have this used as part of my project for others to take ownership on profiles which would more than likely have more items than my profile. I still decided to press forward with this and later found the second issue: takeown.exe would not reliably grant ownership completely down the tree of subfolders. This was a huge issue and would not be acceptable with the customer.

Take Ownership using PowerShell and Set-ACL

The next idea was to grab the ACL object of a folder elsewhere in the user’s home directory that had good permissions and then change the owner in that ACL object to ‘Builtin\Administrators” and the apply it to the profile folder.

$ACL = Get-ACL .\smithb
$Group = New-Object System.Security.Principal.NTAccount("Builtin", "Administrators")
$ACL.SetOwner($Group)
Set-Acl -Path .\smithb\profile.v2 -AclObject $ACL

Sounds good, right? Well, not really due to some un-foreseen issues. Because the accounts do not have the proper user rights (seTakeOwnershipPrivilege, SeRestorePrivilege and SeBackupPrivilege), this would fail right away with an ‘Access Denied’ error. Fine, I can add those privileges if needed and continue on from there. Well, it doesn’t quite work that way either because only the directories would propagate these permissions but the files wouldn’t get ownership.

Set-Owner Function

The final thing that I came up with followed a similar idea as my second attempt, but makes sure to allow for recursion and files and folders as well as allowing either ‘Builting\Administrators’ or another account to have ownership of files and folders. To do this I dove into the Win32 API to first allow the account to elevate the tokens that I have mentioned before.

Try {
[void][TokenAdjuster]
} Catch {
$AdjustTokenPrivileges = @"
using System;
using System.Runtime.InteropServices;

public class TokenAdjuster
{
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
    ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
    [DllImport("kernel32.dll", ExactSpelling = true)]
    internal static extern IntPtr GetCurrentProcess();
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr
    phtok);
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool LookupPrivilegeValue(string host, string name,
    ref long pluid);
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    internal struct TokPriv1Luid
    {
        public int Count;
        public long Luid;
        public int Attr;
    }
    internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
    internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
    internal const int TOKEN_QUERY = 0x00000008;
    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
    public static bool AddPrivilege(string privilege)
    {
        try
        {
            bool retVal;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
            retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
            return retVal;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public static bool RemovePrivilege(string privilege)
        {
        try
        {
            bool retVal;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_DISABLED;
            retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
            retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
            return retVal;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
"@
Add-Type $AdjustTokenPrivileges
}

#Activate necessary admin privileges to make changes without NTFS perms
[void][TokenAdjuster]::AddPrivilege("SeRestorePrivilege") #Necessary to set Owner Permissions
[void][TokenAdjuster]::AddPrivilege("SeBackupPrivilege") #Necessary to bypass Traverse Checking
[void][TokenAdjuster]::AddPrivilege("SeTakeOwnershipPrivilege") #Necessary to override FilePermissions

This allows me to traverse the directory tree and set ownership on the files and folders. If I cannot take ownership on a file or folder (because inheritance is not allowed from the parent folder), then it moves up a level to grant Full Control to to parent folder, thus allowing me to take ownership on the folder or file below it.

Process {
    ForEach ($Item in $Path) {
        Write-Verbose "FullName: $Item"
        #The ACL objects do not like being used more than once, so re-create them on the Process block
        $DirOwner = New-Object System.Security.AccessControl.DirectorySecurity
        $DirOwner.SetOwner([System.Security.Principal.NTAccount]$Account)
        $FileOwner = New-Object System.Security.AccessControl.FileSecurity
        $FileOwner.SetOwner([System.Security.Principal.NTAccount]$Account)
        $DirAdminAcl = New-Object System.Security.AccessControl.DirectorySecurity
        $FileAdminAcl = New-Object System.Security.AccessControl.DirectorySecurity
        $AdminACL = New-Object System.Security.AccessControl.FileSystemAccessRule('Builtin\Administrators','FullControl','ContainerInherit,ObjectInherit','InheritOnly','Allow')
        $FileAdminAcl.AddAccessRule($AdminACL)
        $DirAdminAcl.AddAccessRule($AdminACL)
        Try {
            $Item = Get-Item -LiteralPath $Item -Force -ErrorAction Stop
            If (-NOT $Item.PSIsContainer) {
                If ($PSCmdlet.ShouldProcess($Item, 'Set File Owner')) {
                    Try {
                        $Item.SetAccessControl($FileOwner)
                    } Catch {
                        Write-Warning "Couldn't take ownership of $($Item.FullName)! Taking FullControl of $($Item.Directory.FullName)"
                        $Item.Directory.SetAccessControl($FileAdminAcl)
                        $Item.SetAccessControl($FileOwner)
                    }
                }
            } Else {
                If ($PSCmdlet.ShouldProcess($Item, 'Set Directory Owner')) {                        
                    Try {
                        $Item.SetAccessControl($DirOwner)
                    } Catch {
                        Write-Warning "Couldn't take ownership of $($Item.FullName)! Taking FullControl of $($Item.Parent.FullName)"
                        $Item.Parent.SetAccessControl($DirAdminAcl) 
                        $Item.SetAccessControl($DirOwner)
                    }
                }
                If ($Recurse) {
                    [void]$PSBoundParameters.Remove('FullName')
                    Get-ChildItem $Item -Force | Set-Owner @PSBoundParameters
                }
            }
        } Catch {
            Write-Warning "$($Item): $($_.Exception.Message)"
        }
    }
}
End {  
    #Remove priviledges that had been granted
    [void][TokenAdjuster]::RemovePrivilege("SeRestorePrivilege") 
    [void][TokenAdjuster]::RemovePrivilege("SeBackupPrivilege") 
    [void][TokenAdjuster]::RemovePrivilege("SeTakeOwnershipPrivilege")
}

Using this approach, I was able to accurately take ownership on all of the items as well as not facing major slowdown (it was roughly 30 seconds slower than the UI approach). Seemed like a good tradeoff to me.

Here are a couple of examples of the function in action:

Set-Owner -Path .\smithb\profile.v2 -Recurse -Verbose

image

Set-Owner -Path .\smithb\profile.v2 -Recurse -Verbose -Account 'WIN-AECB72JTEV0\proxb'

image

The function is available to download from the following link:

http://gallery.technet.microsoft.com/scriptcenter/Set-Owner-ff4db177

About these ads

About Boe Prox

Microsoft PowerShell MVP working as a Senior Systems Administrator
This entry was posted in powershell and tagged , , . Bookmark the permalink.

12 Responses to Changing Ownership of File or Folder Using PowerShell

  1. Matt Maguire says:

    Just tried using your function, but didn’t get anywhere. The server in questions is 2008 R2 running PowerShell 3.0. Do I need PowerShell 4 to get this to work? Thanks!

    • Matt Maguire says:

      More specifically, after adding the function to my System32 directory I ran ” set-owner.ps1 -path .\userprofile.V2 -recurse -verbose -account ‘domain\myusername’” under the domain admin account. There was no output, just a new Prompt. After logging in as myself to the server and trying to pen the folder, I found I could not browse or take ownership of the file. I presume I left out a necessary step or two. Any thoughts? Thanks!

  2. f1refoxy says:

    hello,
    Thanks for this Post!
    for my needs, I’m happy with the takeown.exe solution for that problem.
    I want to share my script – it changes all folder (testfolders) und subfolders owners to the “Adminisrators” Group.

    Get-ChildItem E:\testfolders |Where-Object {$.PSIsContainer -eq $true} | ForEach-Object {$workpath = $.FullName;Invoke-Expression -Command ‘takeown.exe /F “$workpath” /A /r /D N’ }

  3. DarkLite1 says:

    Thank you Boe, great function! I left a question on the Microsoft Scriptcenter, as I’m having some difficulties with the ‘-Recurse’ option for regular users.

  4. Johnny says:

    Great script, just one question: how can I write the verbose output to log file?

  5. Keith Wade says:

    I tried running your script on our system today and it said “Unable to find type [TokenAdjuster]. Make sure that the assembly that contains this type is loaded.”

    Any ideas as to why this would happen?

    • Boe Prox says:

      Hmm.. I am not sure as it should attempt to load the type and if it fails, then it will compile the C# code that contains the type. I won’t be able to do much investigating for a week or so but can take a look at it when I am available. Until then, have you tried to run through the code in chunks to make sure it is working properly?

      • Keith Wade says:

        I’m not quite sure that I ran your code the right way. Anyways, we just got Icacls working to do our ownership changes instead.

  6. An opportunity presented itself to test your script out ;)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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