PowerShell Script taking too long to delete empty folders RRS feed

  • Question

  • I am running a PowerShell Script on a shared windows 2008 R2 server via a remote computer. The script is supposed to delete empty folders older than 45 days. But it's taking too long to delete even the first folder. However - I would concede that the folder tree is quite complicated and has as many as 17k folders in total with 60k+ files in them with several complicated branchings. Following is the piece I am using-

    Get-ChildItem -LiteralPath $Delete_APAC -Force -Exclude $Keep_this_folder , $Keep_this_folder2 , $Keep_this_folder3 , $Keep_this_folder4 -Recurse|Where-Object {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath $_.Fullname -Force -Recurse).Count -eq 0 -and ($_.LastWriteTime -lt $regional_limit -or $_.CreationTime -lt $regional_limit)}|Remove-Item -Recurse -Force -Verbose

    I ran this about 17 hours ago and still have failed to see a single folder getting deleted. 
    My guess is that the script is first taking a list of all the empty folders, because as I mapped to the shared drive from the remote comp and ran the script without the remove item bit and it still was taking time. However, when I removed the second pipeline too- it started listing the folders right away. Although, there is an empty folder older than 45 days in the drive right in the beginning- then why it didn't list that one right away?

    Here's another piece I am running in the same environment for deleting files older than 30 days- this also takes time because of the huge volume of files. But, it doesn't take as long (starts deleting as soon as it finds a file to delete) even with the number of files being about 3-4 times the number of folders. Here's the file deletion piece-

    Get-Item -Path $Delete_APAC -Force -exclude $Keep_this_folder,$Keep_this_folder2|Get-ChildItem -Recurse|Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $regional_limit}|Remove-Item -Recurse -Force -Verbose

    Could anyone suggest improvements to this script to make both faster if possible (even if not- I could settle for a bargain with a solution only for the first one :-) )?
    • Moved by Bill_Stewart Friday, April 28, 2017 8:38 PM This is not "fix/debug/rewrite my script for me" forum
    Wednesday, March 29, 2017 8:18 AM

All replies

  • What are you trying to do in simple language. Your code is completely impossible to understand.

    Where did you find this script? Can you ask the author to tell you what it is supposed to do?


    Wednesday, March 29, 2017 7:10 PM
  • I am the author of the script and it is supposed to delete empty folders older than x days.
    Wednesday, March 29, 2017 8:28 PM
  • Get-ChildItem d:\test -Directory -Recurse| 
    	Where-Object{ $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 } | 
    	Remove-Item -force -whatIf


    Wednesday, March 29, 2017 9:31 PM