# Folder to unlock
$Folder = "D:\Users\OldUser\Documents"
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Warning "Run this script as Administrator."; return
}
$Admins = "*S-1-5-32-544" # Built-in Administrators (any OS language)
$User = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$Queue = [System.Collections.Generic.Queue[string]]::new()
$Queue.Enqueue($Folder)
while ($Queue.Count) {
$Dir = $Queue.Dequeue()
# Own + grant the folder itself, so it becomes listable
takeown /f "$Dir" /a *> $null
if ($LASTEXITCODE) { Write-Warning "takeown failed: $Dir" }
icacls "$Dir" /grant "${Admins}:(OI)(CI)F" "${User}:(OI)(CI)F" /C /Q > $null
if ($LASTEXITCODE) { Write-Warning "grant failed: $Dir" }
# Own everything directly inside it (files + subfolders)
takeown /f "$Dir\*" /a *> $null
try { $Subs = Get-ChildItem -LiteralPath $Dir -Directory -Force -ErrorAction Stop }
catch { Write-Warning "Still cannot list: $Dir"; continue }
foreach ($S in $Subs) {
if (-not ($S.Attributes -band [IO.FileAttributes]::ReparsePoint)) { $Queue.Enqueue($S.FullName) }
}
}
# Everything is owned and listable now: grant on all files recursively
icacls "$Folder" /grant "${Admins}:(OI)(CI)F" "${User}:(OI)(CI)F" /T /C /Q > $null
if ($LASTEXITCODE) { Write-Warning "Some items failed during the final grant." }
Write-Host "Done: Administrators own it, Administrators + $User have Full Control on $Folder"