Last active
February 19, 2019 02:24
-
-
Save mavaddat/d1ca46314f83fb3fc710206b78c5d4ca to your computer and use it in GitHub Desktop.
This script recursively deletes e-book library directories that have no books in them. It does this by checking for empty directories or directories with only OPF files in them. It then runs again to check for empty directories (to include the directories it may have just emptied).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ebookLibraryPath = '.\OneDrive\Documents\Ebook Library\' | |
Function Get-Empties { | |
PARAM($targetPath) | |
Return Get-ChildItem -Path $targetPath -Recurse | Where { $_.PsIsContainer -eq $true } | Where { $_.GetDirectories().Count -eq 0 -and ($_.GetFiles().Count -eq 0) -or ($_.GetFiles().Count -eq 1 -and $_.GetFiles().Name -match "(?i)(.*?)\.opf$")} | |
} | |
$failed = @{} | |
$toEmpty = Get-Empties $ebookLibraryPath | |
Function Write-Log { | |
Param ( [parameter(Mandatory=$true, | |
ValueFromPipeline=$true)] | |
[string]$logMessage, | |
[PSDefaultValue(Help = "Will create a log file in the same directory as the script is run")] | |
[string]$Logfile = ".\$(gc env:computername)-delete-dirs.log") | |
Add-Content $Logfile -value $($(Get-Date).ToString() + ": " + $logMessage) | |
} | |
while($toEmpty.Count -gt 0) { | |
try { | |
foreach($dir in $toEmpty){Write-Log "Deleting $($dir.FullName) which has LastWriteTime $($dir.LastWriteTime.ToString())"; Remove-Item -LiteralPath $dir.PSPath -Force -Recurse -Confirm} | |
} | |
catch { | |
$ErrorMessage = $_.Exception.Message | |
$FailedItem = $_.Exception.ItemName | |
Write-Error -Exception $_.Exception | |
$failed.Add($failed.Count+1,$dir) | |
} | |
$toEmpty = Get-Empties $ebookLibraryPath | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment