Delete Empty Folders in PowerShell

Delete empty folders in PowerShell

There are multiple ways that we can use to delete the empty folders in PowerShell but before going into the details, let’s have a look at the following directory structure to know how many and which folders are empty.

Now, let’s dive into the possible solutions to delete empty folders.

Using the Remove-Item with Get-ChildItem Cmdlet

Use Remove-Item with Get-ChildItem to remove empty folders in PowerShell.

Here, we used the Get-ChildItem cmdlet to get all the directories in the E:/testAlpha folder and its subfolders recursively. We then used the Where-Object cmdlet to filter the results only to include directories with no files.

Finally, we used the Remove-Item cmdlet to delete all empty directories. The -Force parameter was used to remove the directories without confirmation, and -Recurse was used to remove the directories and their subfolders.

In case, you want to recursively remove empty folders, use following solution:

We added sort-object cmdlet here to reverse sort by the directory’s FullName. This will always ensure we process children before parents.

Using the Get-ChildItem and ForEach-Object

Use the Get-ChildItem cmdlet with the ForEach-Object loop to remove empty folders in PowerShell.

This method uses a similar approach as the previous example, but it uses a ForEach-Object loop to iterate through the empty directories and remove them one by one.

Using the User-defined Function

Create a function to remove empty folders in PowerShell.

The above method used the cmdlets and loop to remove the empty functions; we wrapped it in the function Remove-EmptySubfolders to make the code more organized and easy to manage and understand.

This method used a custom function; we named Remove-EmptySubfolders that accepted a path as a parameter. Inside the function, it used the Get-ChildItem cmdlet and Where-Object filter to get all the empty directories and then we used the Remove-Item cmdlet to delete them.

In all the examples above, you can change the path of the folder that you want to delete the empty folders. Also, you can use the -WhatIf parameter to test the results before running the command on the actual folders.

That’s all about how to delete empty folders in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *