如何使用 PowerShell 删除空文件和文件夹?

powershellmicrosoft technologiessoftware & coding

要删除空文件和文件夹,我们首先需要检索列表,这在之前的文章中已经介绍过了。

示例

在本文中,我们使用的逻辑是:如果找到空文件或文件夹,就将其删除。要实现该逻辑,请使用以下脚本。

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
      }
}

上述命令将从 C:\temp 路径 中删除空文件和文件夹/子文件夹。

输出

您将看到类似如下的输出。



相关文章