Montag, 2. Mai 2016

Delete huge folder structures where 260 character limit will stops you


Get annoyed by this fricking stupid path length limit of 260 characters when you just want a huge Folder send down the digital Jordan.
I needed this script to kill a folder structure on a Netapp FAS over CIFS with alot of personal folders (old profiles) with alot messed up ACLs. Be sure that you run it with a user which is in Administrator group.

https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath

This PS script walk recursivly through huge folder structures and rename them beginning from top to down 0-9999 before delete them in reverse order.

function Kill-FilePathLimit ([string]$fatpath)
{
    $list=Get-ChildItem -Directory $fatpath
    if ($list) {
        0..$($list.count - 1)|%{
            try{
                Rename-Item $list[$_].FullName $("{0:D4}" -f $_) -ErrorAction Stop
            } catch {
                $AccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name,"FullControl","Allow")
                $ICH = New-Object System.Security.Principal.NTAccount([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
                $ACL=Get-Acl $list[$_].FullName
                $acl.SetOwner($ICH)
                Set-Acl $list[$_].FullName -AclObject $acl
                $acl.SetAccessRule($AccessRule)
                Set-Acl $list[$_].FullName
                Rename-Item $list[$_].FullName $("{0:D4}" -f $_) -ErrorAction Stop
            }
        }
        Get-ChildItem -Directory $fatpath|%{
            Kill-FilePathLimit $_.FullName
        }
    } else {
        Remove-Item -Recurse $fatpath -Force -Confirm:$false
    }
}