Forum Discussion

mahipundir's avatar
mahipundir
Copper Contributor
Oct 23, 2019
Solved

Delete folder x

Hello fellow humans,  I'm using this script to delete folders which are older than 15days or 5 days.    # $limit = (Get-Date).AddDays(-15) $path = "xxxx\path" # Delete files older than the $limi...
  • ChrisBradshaw's avatar
    Jan 20, 2020

    mahipundir 

    Get-ChildItem -path $path -Recurse -Force -Directory

    will create a list of (sub) directories, and then you can filter for empty directories by checking for members of this list with no child items.

    Where-Object {!($_ |Get-ChildItem -Recurse)}

    So put together that would give:

    Get-ChildItem -path $Path -Recurse -Force -Directory | Where-Object {!($_ |Get-ChildItem -Recurse)}

    However, if a folder contains no files, but does contain (empty) subfolders then it won't appear in this list, so assuming you want to delete folders which might contain subfolders but don't have any files anywhere down the tree then you need something like:

    Get-ChildItem -path $Path -Recurse -Force -Directory | Where-Object {!($_ |Get-ChildItem -Recurse -File)} 

     

    And then add the actual deletion as before:

    Get-ChildItem -path $Path -Recurse -Force -Directory | Where-Object {!($_ |Get-ChildItem -Recurse -File)} | Remove-Item -Force -Recurse 

     

Resources