$root = "C:\Users\Karthik\Documents\GitRepositories\Calculations\Dipolar-Gas-Simulator\Results\Data_3D\GradientDescent\Phi020" # Step 1: Delete all files except 'psi_gs.mat' Get-ChildItem -Path $root -Recurse -File -Force | Where-Object { $_.Name -ne "psi_gs.mat" } | ForEach-Object { try { Remove-Item -Path $_.FullName -Force -ErrorAction Stop Write-Output "Deleted: $($_.FullName)" } catch { Write-Warning "Failed to delete: $($_.FullName)" } } # Step 2: Delete all empty directories (deepest first) Get-ChildItem -Path $root -Recurse -Directory -Force | Sort-Object FullName -Descending | ForEach-Object { if (-not (Get-ChildItem -Path $_.FullName -Force)) { try { Remove-Item -Path $_.FullName -Force -ErrorAction Stop Write-Output "Deleted empty folder: $($_.FullName)" } catch { Write-Warning "Failed to delete folder: $($_.FullName)" } } }