This may seem a little convoluted but it does work! See comments in code for logic.
Clear-Host
#*** Setup ***
$BasePath = "N:\Scripts"
$DeletedFiles = 0
$NonDeletedFiles = 0
$DeletedDirs = 0
$NonDeletedDirs = 0
#Gather all directories under $BasePath
$GCIArgs = @{Path = "$BasePath"
Directory = $True
Recurse = $True
}
[System.Collections.ArrayList]$Dirs = (Get-ChildItem @GCIArgs).FullName
[Void]$Dirs.Add("$BasePath") #Add base path to deletion list!
#Sort dirs longest first to allow deletion in proper order
$SDirs = $Dirs | Sort-Object { $_.length } -Descending
For ($Cntr = 0; $Cntr -lt $SDirs.Count; $Cntr++) {
$GCIArgs = @{Path = "$($SDirs[$($Cntr)])"
File = $True
ErrorAction = "SilentlyContinue"
}
$FilesToDel = Get-ChildItem @GCIArgs
If ($Null -ne $FilesToDel) {
ForEach ($File in $FilesToDel) {
$RIArgs = @{LiteralPath = "$($File.FullName)"
Force = $True
ErrorAction = "Stop"
}
Try {
Remove-Item @RIArgs
$DeletedFiles += 1
}
Catch {
"Could not delete File: $File "
$NonDeletedFiles += 1
}
} #End ForEach ($File in $FilesToDel)
} #End If ($FilesToDel.Count -gt 0)
#Remove the containing Directory!
Try {
$RIArgs.LiteralPath = "$($SDirs[$($Cntr)])"
#Note -Recurse necessary to prevent popup msg reporting
# child directories when none exist, not sure why?
Remove-Item @RIArgs -Recurse
$DeletedDirs += 1
}
Catch {
"Could not Delete Directory: $($SDirs[$($Cntr)])"
$NonDeletedDirs += 1
}
} #End For ($Cntr = 0; $Cntr -lt $SDirs.Count; $Cntr++)
"`nRun Statistics:"
"$DeletedDirs Directories were Deleted"
"$DeletedFiles Files were Deleted"
"$NonDeletedDirs Directories could NOT be Deleted"
"$NonDeletedFiles Files could NOT be Deleted!"
Sample Output:
Run Statistics:
135 Directories were Deleted:
2243 Files were Deleted
0 Directories could NOT be Deleted
0 Files could NOT be Deleted!
Note: before I got the bugs out I was getting messages about files and directories that could not be deleted.