Wednesday, June 25, 2025

Power shell script - Delete-All-Folders-Except-Specified

#—— Configuration ——#

# Path to clean up

$basePath = "K:\AY\AOSService_44"


# List A: folder names to KEEP

$excludedFolders = @(

    "AxTable",

    "AxTableExtension",

    "AxView",

    "AxViewExtension",

    "AxDataEntityView",

    "AxDataEntityViewExtension",

    "AxQuery",

    "AxQuerySimpleExtension"

)


# Build a case‐insensitive HashSet for fast lookups

$excludedSet = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)

foreach ($name in $excludedFolders) { $excludedSet.Add($name) }



#—— Script Logic ——#

# 1. Grab every directory under the base path

$allDirs = Get-ChildItem -Path $basePath -Directory -Recurse


# 2. Sort by depth (deepest first) so children are processed before parents

$sortedDirs = $allDirs | Sort-Object {

    $_.FullName.Split([IO.Path]::DirectorySeparatorChar).Count

} -Descending


foreach ($dir in $sortedDirs) {

    # 3a. If this folder IS in List A, skip it

    if ($excludedSet.Contains($dir.Name)) {

        Write-Host "Skipping (excluded): $($dir.FullName)"

        continue

    }


    # 3b. If it contains ANY descendant folder in List A, skip it

    $hasExcludedDescendant = Get-ChildItem -Path $dir.FullName -Directory -Recurse |

        Where-Object { $excludedSet.Contains($_.Name) } |

        Select-Object -First 1


    if ($hasExcludedDescendant) {

        Write-Host "Skipping (contains excluded subfolder): $($dir.FullName)"

        continue

    }


    # 4. Otherwise, delete it

    try {

        Remove-Item -Path $dir.FullName -Recurse -Force -ErrorAction Stop

        Write-Host "Deleted: $($dir.FullName)"

    }

    catch {

        Write-Warning "Failed to delete $($dir.FullName): $_"

    }

}