How To Change Ownership Of Files In Windows 10
While working on a projection recently, I needed to detect an piece of cake way to take buying of a profile folder and its subfolders to let our support staff to either delete the profile or be able to traverse the binder to help troubleshoot issues. Typically, one could apply Explorer to notice the binder and then take ownership and exist done with it. But the goal was to come up with a command line solution that not only worked quickly, merely didn't miss out on a file or binder.
The brief groundwork on this is that roaming profiles sometimes would go inaccessible to our support staff in that only the user account and System would have access to the contour folder and its sub-folders and files. Besides, buying of those objects were by the user account. This created problems with deleting accounts and troubleshooting profile related issues.
Before showing the solution that I came upwardly 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 buying to Builtin\Administrators. Sure it wasn't a PowerShell approach, but it met the requirements of what I wanted to practise…or so I thought.
The commencement trouble is that it is slow. I kicked it off on my own profile (considering it is always more fun to test on yourself than others) and plant that information technology would accept upwards of ten minutes vs. the ~2 infinitesimal UI approach. Obviously this is an event if I expect to accept this used as function of my project for others to take ownership on profiles which would more than than likely have more than items than my profile. I still decided to printing forrad with this and later on constitute the 2d issue: takeown.exe would non reliably grant ownership completely down the tree of subfolders. This was a huge issue and would not be adequate 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 expert permissions and then alter the owner in that ACL object to 'Builtin\Administrators" and the use it to the profile folder.
$ACL = Become-ACL .\smithb $Grouping = New-Object System.Security.Principal.NTAccount("Builtin", "Administrators") $ACL.SetOwner($Grouping) Gear up-Acl -Path .\smithb\profile.v2 -AclObject $ACL Sounds good, right? Well, not really due to some un-foreseen bug. Because the accounts practice not accept 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 Office
The concluding thing that I came up with followed a similar idea as my second attempt, just makes sure to allow for recursion and files and folders besides every bit allowing either 'Builting\Administrators' or another account to accept 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 = truthful)] internal static extern IntPtr GetCurrentProcess(); [DllImport("advapi32.dll", ExactSpelling = truthful, 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, cord proper noun, ref long pluid); [StructLayout(LayoutKind.Sequential, Pack = i)] 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(cord privilege) { try { bool retVal; TokPriv1Luid tp; IntPtr hproc = GetCurrentProcess(); IntPtr htok = IntPtr.Null; retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); tp.Count = one; tp.Luid = 0; tp.Attr = SE_PRIVILEGE_ENABLED; retVal = LookupPrivilegeValue(cipher, privilege, ref tp.Luid); retVal = AdjustTokenPrivileges(htok, faux, ref tp, 0, IntPtr.Aught, IntPtr.Zippo); return retVal; } take hold of (Exception ex) { throw ex; } } public static bool RemovePrivilege(cord privilege) { try { bool retVal; TokPriv1Luid tp; IntPtr hproc = GetCurrentProcess(); IntPtr htok = IntPtr.Zilch; retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); tp.Count = 1; tp.Luid = 0; tp.Attr = SE_PRIVILEGE_DISABLED; retVal = LookupPrivilegeValue(zippo, privilege, ref tp.Luid); retVal = AdjustTokenPrivileges(htok, imitation, ref tp, 0, IntPtr.Zero, IntPtr.Zero); return retVal; } catch (Exception ex) { throw ex; } } } "@ Add-Blazon $AdjustTokenPrivileges } #Actuate 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 ready ownership on the files and folders. If I cannot accept ownership on a file or binder (because inheritance is non immune from the parent folder), then it moves upward a level to grant Total Control to to parent folder, thus assuasive me to take ownership on the folder or file below information technology.
Process { ForEach ($Detail in $Path) { Write-Verbose "FullName: $Particular" #The ACL objects exercise non similar being used more than once, so copy them on the Process block $DirOwner = New-Object System.Security.AccessControl.DirectorySecurity $DirOwner.SetOwner([System.Security.Principal.NTAccount]$Business relationship) $FileOwner = New-Object System.Security.AccessControl.FileSecurity $FileOwner.SetOwner([Organisation.Security.Main.NTAccount]$Business relationship) $DirAdminAcl = New-Object System.Security.AccessControl.DirectorySecurity $FileAdminAcl = New-Object Arrangement.Security.AccessControl.DirectorySecurity $AdminACL = New-Object Organisation.Security.AccessControl.FileSystemAccessRule('Builtin\Administrators','FullControl','ContainerInherit,ObjectInherit','InheritOnly','Allow') $FileAdminAcl.AddAccessRule($AdminACL) $DirAdminAcl.AddAccessRule($AdminACL) Try { $Item = Get-Particular -LiteralPath $Item -Forcefulness -ErrorAction Stop If (-NOT $Item.PSIsContainer) { If ($PSCmdlet.ShouldProcess($Item, 'Fix File Owner')) { Endeavour { $Item.SetAccessControl($FileOwner) } Grab { Write-Alert "Couldn't take ownership of $($Item.FullName)! Taking FullControl of $($Particular.Directory.FullName)" $Item.Directory.SetAccessControl($FileAdminAcl) $Item.SetAccessControl($FileOwner) } } } Else { If ($PSCmdlet.ShouldProcess($Detail, 'Set Directory Possessor')) { Effort { $Item.SetAccessControl($DirOwner) } Catch { Write-Warning "Couldn't have ownership of $($Item.FullName)! Taking FullControl of $($Item.Parent.FullName)" $Particular.Parent.SetAccessControl($DirAdminAcl) $Item.SetAccessControl($DirOwner) } } If ($Recurse) { [void]$PSBoundParameters.Remove('FullName') Go-ChildItem $Item -Force | Set-Possessor @PSBoundParameters } } } Catch { Write-Warning "$($Item): $($_.Exception.Message)" } } } Finish { #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 likewise as non facing major slowdown (it was roughly 30 seconds slower than the UI approach). Seemed like a good tradeoff to me.
Hither are a couple of examples of the office in activity:
Set-Possessor -Path .\smithb\profile.v2 -Recurse -Verbose
Set-Owner -Path .\smithb\profile.v2 -Recurse -Verbose -Account 'WIN-AECB72JTEV0\proxb'
The function is bachelor to download from the post-obit link:
http://gallery.technet.microsoft.com/scriptcenter/Ready-Owner-ff4db177
Source: https://learn-powershell.net/2014/06/24/changing-ownership-of-file-or-folder-using-powershell/
Posted by: valliereslosicessir.blogspot.com

0 Response to "How To Change Ownership Of Files In Windows 10"
Post a Comment