Powershell command to delete subfolders without deleting the root Powershell command to delete subfolders without deleting the root powershell powershell

Powershell command to delete subfolders without deleting the root


So you are looking to delete All Items inside Empty Subfolders or all items in General?

This will delete all Folders or Items in General inside of the Directory "C:\abc\"

$path = "C:\abc\"Get-ChildItem -Path $path -Recurse| Foreach-object {Remove-item -Recurse -path $_.FullName }

This will delete all Folders that dont have any items in them.

$path = "C:\abc\"Get-ChildItem -Path $path -Recurse | Where-Object {(Get-ChildItem $_.FullName).Count -eq 0} |Foreach-object {Remove-item -Recurse -path $_.FullName }

´This will look inside "C:\abc\" Get all the children and delete all empty Directories inside the Children in your example this would be Item1,Item2,...

$Path = "C:\abc\"$itemFolders= Get-ChildItem -Path $Path$itemFolders| Foreach-Object {    Get-ChildItem -Path $_.FullName |    Where-Object {(Get-ChildItem $_.FullName).Count -eq 0} |     Foreach-object {Remove-item -Recurse -path $_.FullName }}

Just a quick and dirty bit of Code as I dont have much time, hope I could be of help.

EDIT: Here is what i came up with, its not as performant as I'd like but it gets the job done and is fairly quick, try it out for yourself it worked for me - even threw in a couple of comments and output to clarify what's going on.

$Path="C:\abc\"$itemFolders = Get-ChildItem $Path#Get All Folders inside$AllFolders = $itemFolders | Get-ChildItem -Recurse | Where-Object {$_.PSIsContainer} | Select -Property FullName#First delete all files older than 30 days$itemFolders | Get-ChildItem -Recurse -File | ForEach-Object{    $limit = (Get-Date).AddDays(-30)    if($_.LastWriteTime -lt $limit)    {        "{0} hasn't been modified in the last 30 days deleting it" -f $_.FullName        Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue            }}#Check if there are files inside that are not containers$AllFolders | ForEach-Object{    $files = Get-ChildItem -File -Recurse -Path $_.FullName    $directories = Get-ChildItem -Directory -Recurse -Path $_.FullName    #If There are any files inside the folder dont delete it.    if($files.Count -gt 0)    {        "Found {0} files inside {1} do not delete this" -f $files.Count, $_.FullName    }    #If There are no files and no directories inside delete it.    elseif($files.Count -eq 0 -and $directories.Count -eq 0)    {        "Empty Folder {0} deleting it" -f $_.FullName        Remove-Item -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue    }    #If there are no files and empty directories inside delete it.    elseif($files.Count -eq 0 -and $directories.Count -gt 0)    {        "No Files but directories found in {0} since its recursive delete it" -f $_.FullName        Remove-Item -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue            }}