Skip to content

Instantly share code, notes, and snippets.

@573
Last active August 19, 2024 20:08
Show Gist options
  • Save 573/2b56a4b74b092f53df73aec7e2496bb0 to your computer and use it in GitHub Desktop.
Save 573/2b56a4b74b092f53df73aec7e2496bb0 to your computer and use it in GitHub Desktop.
powershell tip remove folders and contents recursively that are buried deeper than windows path length

had the rare case of a folder created by whatever process folder named cd C:\Users\user\AppData\Local\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\deep\deep\down

which made both takeown /f "C:\Users\user" /S HOSTNAME /u domain\username /r /d J and icacls "C:\Users\user" /setowner "domain\username" /T /C (was trial and error icacls, see at bottom what is the right approach once buried folder is removed) terminate prematurely due to the path length barrier.

cd C:\Users\user\AppData\Local\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\Anwendungsdaten\deep\deep\down
$path = (dir .\subfolder_in_buried_folder\anyfile_therein).FullName
$object = New-Object -ComObject Scripting.FileSystemObject
$output = $object.GetFile($path)
Write-Host "`n`n The short path of this directory is" $output.shortpath.trim("anyfile_therein")
# with that path now I was able to remove the folder
cd \
&cmd.exe /c rd /s /q C:\Users\User~1\AppData\Local\ANWEND~1

icacls:

Get-ChildItem C:\Users\user |
>> ForEach-Object {
>>   icacls $_.FullName /reset /t /c
>> }

here still, catch some too long file names i. e. in C:\Users\user\Anwendungsdaten\Mozilla\Firefox\Profiles\ via 8.3 technique above, with that (luckily just one) very large filename did this:

cd C:\Users\dkahlenberg\AppData\Roaming\Mozilla\Firefox\Profiles\sfassdf.jhjh\storage\archives\0\2023-04-04\default\
del file* # was: file++++C++Users+user+Documents+faaafdasfasdafasdfadsfafa

Afterwards repeat:

$ret = icacls "C:\Users\user" /setowner "domain\username" /T /C 2> err.log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment