How to delete empty files and folders using PowerShell?

To delete empty files and folders, we need to first retrieve the list and which has been shown in the earlier articles.


In this article, we are using the logic that if we find an empty file or folder we will delete them. To implement that logic, use the below script.

gci C:\Temp -Recurse | foreach {
   if($_.Length -eq 0){
      Write-Output "Removing Empty File $($_.FullName)"
      $_.FullName | Remove-Item -Force
   if( $_.psiscontainer -eq $true){
      if((gci $_.FullName) -eq $null){
         Write-Output "Removing Empty folder $($_.FullName)"
         $_.FullName | Remove-Item -Force

The above command will remove empty files and folders/sub-folders from the C:\temp path.


You will see the output something like this.