Re: Delete empty folders (one-click function)
Posted: 2023-09-22, 18:13 UTC
PowerShell_DeletEmptyFolders_Display_Log_Remove.ps1 [updated]
Note: The updated version addresses the excessive Remove-Item -Verbose output in a way to display only the full paths of the empty directories that are getting deleted.
[modified] Example script output:
https://i.imgur.com/qvvauSe.png
Code: Select all
"creating folders structure [needed only for the testing purposes]:"
$md = '.\empty\empty' ;New-Item $md -force -Type directory >$null; $md
$md = '.\empty\folder' ;New-Item $md -force -Type directory >$null; $md
$md = '.\empty\structure';New-Item $md -force -Type directory >$null; $md
$md = '.\empty\file.txt' ;New-Item $md -force -Type file -value "file">$null; $md
# feel free to remove the above code as soon as you make sure the script is working as intended
"";"working directory:";([System.Environment]::CurrentDirectory)
"";"empty folders that can be deleted:"
$stamp = (Get-Date -format "yyyyMMdd_HHmmssf");$log = $($stamp+'_del.log')
Get-ChildItem (Get-Location) -force -recurse|Where {$_.PSIsContainer -and @(Get-ChildItem -literalPath $_.Fullname -force -recurse|Where {!$_.PSIsContainer}).Length -eq 0}|Select-Object -ExpandProperty FullName|Out-File $log
Get-Content($log)
"";"empty folders actually being deleted:"
Get-ChildItem (Get-Location) -force -recurse|Where {$_.PSIsContainer -and @(Get-ChildItem -literalPath $_.Fullname -force -recurse|Where {!$_.PSIsContainer}).Length -eq 0}|Remove-Item -force -recurse -Verbose -ErrorAction Ignore 4>&1|Foreach-Object {Write-Host ($_.Message -replace '(.*)"(.*)"(.*)','$2') -ForegroundColor Yellow}
"";"see deleted folders list in a log file:";$log
"";pause
[modified] Example script output:
https://i.imgur.com/qvvauSe.png