Pages

søndag 7. april 2013

PowerShell: Delete empty folders

Perhaps after deleting files in TEMP folder, you would like to delete empty folders as well...

First, lets get all the folders:
$FolderList = Get-ChildItem -LiteralPath $env:TEMP -Recurse -ErrorAction SilentlyContinue -Force | Where-Object {$_.PSIsContainer} | Sort-Object @{Expression={$_.FullName.Length}; Ascending=$false}

To list the folders you could execute:
$FolderList | Format-Table -Property LastWriteTime,CreationTime,FullName -AutoSize

Now we would like to loop through each folder and see if it has files, and if not, delete it (but not the folder Low).

$Count = $FolderList.Count

for ($i=0;$i -lt $Count;$i++){
  if(-not (Get-ChildItem -LiteralPath $FolderList[$i].FullName -ErrorAction SilentlyContinue -Force|Select-Object -First 1)) {
    if ($FolderList[$i].Name -ne "Low"){
      Remove-Item -LiteralPath $FolderList[$i].FullName -Force -Recurse -ErrorAction SilentlyContinue -WhatIf
    }
  }
}

To actually delete the folders, remove -WhatIf