Share via


Delete empty folders

Question

Wednesday, April 1, 2015 9:54 PM

Here is my folder structure

D:\FileClenup\Archive\DC01\20150401\xmls

D:\FileClenup\Archive\DC01\20150331\xmls

D:\FileClenup\Archive\DC01\20150402\xmls

D:\FileClenup\Archive\DC01\20150332\xmls

I am deleting empty directories if have in the Archive <g class="gr_ gr_42 gr-alert gr_gramm Punctuation only-ins replaceWithoutSep" data-gr-id="42" id="42">folder</g> but all folders are deleting

Below command is using for delete empty directories in the Archive folder

# Delete Empty Directories

$currentPath= D:\FileClenup\Archive

**                              $emptyDdirectories = Get-ChildItem -Path $currentPath -Recurse | Where {$($_.Attributes) -match "Directory" -and $_.GetFiles().Count -eq 0} | Foreach {**

**        Remove-Item $_.FullName -Recurse -Force}**

                              ###

Please suggest you are thoughts  

All replies (28)

Monday, April 6, 2015 6:16 AM ✅Answered

Hi Kapil,

Please try to run the script below directly, and post back the result:

Get-ChildItem "folder path" -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.fullname).Count -eq 0} |remove-item -whatif

If there is anything else regarding this issue, please feel free to post back.

If you have any feedback on our support, please click here.

Best Regards,

Anna Wang

TechNet Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]


Wednesday, April 1, 2015 10:12 PM

That won't work.  Directories can contain directories and all will be deleted.

¯\(ツ)_/¯


Wednesday, April 1, 2015 10:16 PM

I need to remove **Directory condition **

Please share working command 


Wednesday, April 1, 2015 10:47 PM

Looks like the logic is flawed.

Consider the DC01 folder.  It is a directory.  And it appears to contain no files.  Based on your logic the whole tree under DC01 will be deleted.

You may want to use Get-ChildItem instead of $_.GetFiles().  If a folder contains only folder, leave it alone.


Thursday, April 2, 2015 12:15 AM

I need to delete folder contains only folder has empty .


Thursday, April 2, 2015 9:31 AM | 5 votes

This one works pretty good:

$TargetFolder = "C:\Test"

$Folders = @()
ForEach ($Folder in (Get-ChildItem -Path $TargetFolder -Recurse | Where { $_.PSisContainer }))
{
   $Folders += New-Object PSObject -Property @{
      Object = $Folder
      Depth = ($Folder.FullName.Split("\\")).Count
   }
}
$Folders = $Folders | Sort Depth -Descending

$Deleted = @()
ForEach ($Folder in $Folders)
{
   If ($Folder.Object.GetFileSystemInfos().Count -eq 0)
   {  $Deleted += New-Object PSObject -Property @{
         Folder = $Folder.Object.FullName
         Deleted = (Get-Date -Format "hh:mm:ss tt")
         Created = $Folder.Object.CreationTime
         'Last Modified' = $Folder.Object.LastWriteTime
         Owner = (Get-Acl $Folder.Object.FullName).Owner
      }
      Remove-Item -Path $Folder.Object.FullName -Force
   }
}

$Deleted

**Source: **http://thesurlyadmin.com/2013/01/07/remove-empty-directories-recursively/


Thursday, April 2, 2015 6:39 PM | 1 vote

Thanks to all for sharing you are thoughts .

some folders do not have subdirectories that situation above code get error

D:\FileClenup\Archive\DC01\.xml's 


Thursday, April 2, 2015 7:20 PM | 4 votes

You'll need to "walk the tree" in the right order to do it correctly.  I'd do it with a recursion.

function Remove-EmptyFolder ([String]$path)
{
    #Recursive Call to "Walk the Tree"
    Get-ChildItem -LiteralPath:$path -Directory | ForEach-Object { Remove-EmptyFolder -path:$_ }
    
    #Base Case
    if (@(Get-ChildItem -LiteralPath:$path).Count -eq 0)
    {
        Write-Debug "Deleting Folder $path"
        Remove-Item -LiteralPath:$path -Force
    }
}

$originalDP = $DebugPreference
$DebugPreference = 'Continue'
Remove-EmptyFolder -path:'Your Root Path Here'
$DebugPreference = $originalDP

Thursday, April 2, 2015 8:57 PM

entering to the for loop if there is no sub-directories 

Path =D:\FileClenup\Archive\DC01

ForEach ($Folder in $Folders)
{}

Friday, April 3, 2015 3:14 AM

Hi kapil,

I tested AverageJoeOfToronto's script, which should do the job.

Please also modify the line "Get-ChildItem -LiteralPath:$path -Directory | ForEach-Object { Remove-EmptyFolder -path:$_ }" in the function "Remove-EmptyFolder" to "Get-ChildItem -LiteralPath:$path -Directory | ForEach-Object { Remove-EmptyFolder -path:$($_.fullname) }", Or you may encounter "can't find path" path.

Please also add the "-whatif" parameter to the "Remove-Item" in case of deleting folders by mistake.

If there is anything else regarding this issue, please feel free to post back.

If you have any feedback on our support, please click here.

Best Regards,

Anna Wang

TechNet Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]


Friday, April 3, 2015 1:24 PM

Thanks for you <g class="gr_ gr_19 gr-alert gr_gramm Grammar multiReplace" data-gr-id="19" id="19">are support</g> Anna.

I have tried AverageJoeOfToronto's  script getting error Directory parameter is not found 

Get-ChildItem : A parameter cannot be found that matches parameter name 'Direct
ory'.
At C:\Users\XXX\AppData\Local\Temp\09651948-a759-463c-91ab-20d5
3ca61ff4.ps1:3 char:44
+ Get-ChildItem -LiteralPath:$path -Directory <<<<  | ForEach-Object { Remove-E
mptyFolder -path:$($_.fullname) }
    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem], ParameterB
   indingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Comm
   ands.GetChildItemCommand


Friday, April 3, 2015 1:26 PM

I have tried AverageJoeOfToronto's  script getting error Directory parameter is not found 

You need to upgrade. The -Directory parameter requires at least v3 of PowerShell (v4 is the current version).

Don't retire TechNet! - (Don't give up yet - 13,225+ strong and growing)


Friday, April 3, 2015 1:36 PM

My Production environment has PS version 2.0 

Is there any way to execute the script in 2.0 


Friday, April 3, 2015 1:38 PM | 1 vote

My Production environment has PS version 2.0 

Is there any way to execute the script in 2.0 

You can pipe the output of Get-ChildItem through a Where like so:

Get-ChildItem |
    Where { $_.PsIsContainer }

Don't retire TechNet! - (Don't give up yet - 13,225+ strong and growing)


Friday, April 3, 2015 7:44 PM

Please also modify the line "Get-ChildItem -LiteralPath:$path -Directory | ForEach-Object { Remove-EmptyFolder -path:$_ }" in the function "Remove-EmptyFolder" to "Get-ChildItem -LiteralPath:$path -Directory | ForEach-Object { Remove-EmptyFolder -path:$($_.fullname) }", Or you may encounter "can't find path" path.

Ahh thanks for picking up the error.  My code wasn't really tested.


Friday, April 3, 2015 10:36 PM

 have used below code  but getting pipeline error

<g class="gr_ gr_37 gr-alert gr_gramm Punctuation multiReplace" data-gr-id="37" id="37">forEach-Object :</g> The pipeline failed due to call depth overflow. The call depth
** reached 1001 and the maximum is 1000.**
At C:\Users\kapil_kumar_velpuri\Desktop\2.ps1:4 char:100
+     Get-ChildItem -Path $TargetFolder -Recurse | Where { $_.PSisContainer -eq
** $True } | ForEach-Object <<<<  { Remove-EmptyFolder -path:$($_.fullname) }**
**    + CategoryInfo          : InvalidOperation: (1001:Int32) [ForEach-Object],**
**    PipelineDepthException**
**    + FullyQualifiedErrorId : CallDepthOverflow,Microsoft.PowerShell.Commands.**
**   ForEachObjectCommand**

<g class="gr_ gr_91 gr-alert gr_gramm Punctuation multiReplace" data-gr-id="91" id="91">Out-Default :</g> The pipeline failed due to call depth overflow. The call depth re
ached 1011 and the maximum is 1010.

Code:

function Remove-EmptyFolder ([String]$path)
{
    #Recursive Call to "Walk the Tree"
    Get-ChildItem -Path $TargetFolder -Recurse | Where { $_.PSisContainer -eq $True } | ForEach-Object { Remove-EmptyFolder -path:$($_.fullname) } 
    #Base Case
    if (@(Get-ChildItem -LiteralPath:$path).Count -eq 0)
    {
        Write-Debug "Deleting Folder $path"
        Remove-Item -LiteralPath:$path -Force
    }
}

$originalDP = $DebugPreference
$DebugPreference = 'Continue'
Remove-EmptyFolder -path:'C:\kapil\FileClenup\Archive'
$DebugPreference = $originalDP

Monday, April 6, 2015 11:16 PM

Get-ChildItem "C:\kapil\FileClenup\Archive" -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.fullname).Count -eq 0} |Foreach {Remove-Item $_.FullName -Recurse -Force -whatif}

I have used below and above  commands which showing empty folder got removed but not deleted by physically 

 "C:\kapil\FileClenup\Archive" -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.fullname).Count -eq 0} |remove-item -whatif

Monday, April 6, 2015 11:25 PM

That is the big problem with PowerShell.  It is not easy for non-technicians to understand.  That makes sense since it was designed for technicians and engineers and not en users.

End users should not try to use PowerShell to solve problems.  It will be a very frustrating experience.

I highly recommend that non-technical users should contact consultants to help them work with the more advanced technologies. 

\(ツ)_/


Monday, April 6, 2015 11:34 PM

PowerShell when used as a programming language incurs the same obligation to attention to detail that other programming languages demand.

The "problem" is attracting experienced programmers to PowerShell who are usually committed  to the other programming languages.


Monday, April 6, 2015 11:52 PM

PowerShell when used as a programming language incurs the same obligation to attention to detail that other programming languages demand.

The "problem" is attracting experienced programmers to PowerShell who are usually committed  to the other programming languages.

I don't disagree with this but I do believe that a "scripting" language does not require formal programming training although it wouldn't hurt.  What seems to be missing is the desire by the new Windows users to spend any time studying and researching anything. So many new users believe that all things can be learned by asking questions in "chat rooms" . There are no more scientists and engineers in the modern computer world. I blame this on companies who refuse to send their techs out to training.

\(ツ)_/


Tuesday, April 7, 2015 1:00 AM

here is the issue is the command is saying is deleted but it won't deleted what is the possible causes  who are already faced issues then it will save time 


Tuesday, April 7, 2015 1:31 AM

Hi Kapil,

This is because of the "-whatif" parameter, like I mentioned above, add the "-whatif" parameter to the "Remove-Item" cmdlet in case of deleting folders by mistake.

If you have checked these folders and want to delete them, please remove the "-whatif" parameter in the "Remove-Item" cmdlet.

If there is anything else regarding this issue, please feel free to post back.

If you have any feedback on our support, please click here.

Best Regards,

Anna Wang

TechNet Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]


Tuesday, April 7, 2015 3:44 AM

Thank you Anna its working there is  a bug in my power-shell script 

I will implement and let you know the results 


Monday, April 13, 2015 9:56 AM

Hi Kapil,

I’m writing to just check in to see if the suggestions were helpful. If you need further help, please feel free to reply this post directly so we will be notified to follow it up.

If you have any feedback on our support, please click here.

Best Regards,

Anna Wang

Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]


Monday, June 19, 2017 1:22 PM

works perfectly!  thank you


Friday, March 9, 2018 5:19 PM

Is there a way to exclude directories and sub directories with adding something to the following code? I'm really new to Powershell and can exclude one directory but if there is multiple directories inside that one and if they are empty they are deleted.

Get-ChildItem "folder path" -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.fullname).Count -eq 0} |remove-item -whatif


Friday, March 9, 2018 5:22 PM

Please do not add your questions onto very old posts.  If you have a question please open your own topic.  Post your code and any errors.

\(ツ)_/


Thursday, March 22, 2018 10:41 PM | 2 votes

$Folder = "C:\Temp\Stuff"#Delete All Empty Subfolders in a Parent Folder
Get-ChildItem -Path $Folder -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

#Delete Parent Folder if empty
If((Get-ChildItem -Path $Folder -force | Select-Object -First 1 | Measure-Object).Count -eq 0) {Remove-Item -Path $Folder -Force -Recurse}