Forum Discussion
Delete folder x
- Jan 20, 2020
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
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