19

I'm trying to use Powershell to change owner of a folder, recursively.

I'm basically using this code:

$acct1 = New-Object System.Security.Principal.NTAccount('DOMAIN\Enterprise Admins')
$profilefolder = Get-Item MyFolder
$acl1 = $profilefolder.GetAccessControl()
$acl1.SetOwner($acct1)
set-acl -aclobject $acl1 -path MyFolder

This will change ownership at the first level, but not for any subfolders or files. Is there a way to extend the scope to all content of MyFolder?

Mikael Grönfelt
  • 677
  • 3
  • 7
  • 14

3 Answers3

32

The takeown command does exactly what you're trying to do. It's a regular windows utility.

This snippet will apply ownership to the current user, but you can set it to any user you want.

http://technet.microsoft.com/en-us/library/cc753024(v=ws.10).aspx

takeown /f "c:\folder\subfolder" /r

If you run into trouble make sure you are running the cmd/powershell window with administrator permissions. Same applies to the other powershell specific answer.

scaryman
  • 428
  • 4
  • 6
  • 3
    This doe snot seem to work for setting the owner to a group (Other than "Administrators") – Gert van den Berg Oct 31 '16 at 12:13
  • I suggest adding `/d Y` to suppress the command from asking if you want to take ownership of every folder that gets encountered. E.g., `takeown /f "c:\folder\subfolder" /r /d Y` – JamesQMurphy Jun 08 '23 at 18:05
8

The Set-ACL cmdlet will take the path parameter from the pipe, so the recommended way is to pipe the contents of a directory to set the owner on each item:

dir -r c:\Users\goyuix\temp | set-acl -aclobject $acl1

That will recursively set the owner on all the folders/files in the temp directory in my profile.

Goyuix
  • 3,214
  • 5
  • 29
  • 37
0

Use Get-ChildItem to get all subordinate folders and files, and change the owner for each one of them:

$identityReference = [System.Security.Principal.NTAccount]::new('<new-owner-username>')
Get-Item C:\Path\To\Folder `
    | foreach { $_ ; $_ | Get-ChildItem -Force -Recurse } `
    | foreach { $acl = $_ | Get-Acl; $acl.SetOwner($identityReference); $_ | Set-Acl -AclObject $acl }

I think this is also what takeown.exe and the GUI basically do as well.

Caveat: For this to work you need permissions to read folder contents and ACLs. (I think takeown and the GUI can and do work around some (explicit) missing permissions in some cases.)

Bonus: On Windows 10/2016+ you can set a registry key and might not suffer from the 260 characters file path length limitation when using PowerShell.

argonym
  • 113
  • 4