[Windows] Annhiliator6000's Comic Checker Script

Anything non-Mylar related
Post Reply
Annihilator6000
Posts: 1
Joined: Mon Aug 11, 2014 2:03 am

[Windows] Annhiliator6000's Comic Checker Script

Post by Annihilator6000 »

Hello All,

I created this initially to trawl through my large comic collection, and new bulk downloads of comics, to check for bad files. It got to be pretty tedious to check every directory manually and I wanted a better way to do it. So I created a PowerShell script for it. Then I figured that other Mylar users could get some use out of it, so I'm posting it here.

The rundown of how this script works is that a directory is selected, the script recursively finds all CBR and CBZ files under the selected directory, and then it runs 7-zip's testing option on all of the comics that are found. Any bad comics that it detects can be logged and deleted to the Recycle Bin. Any newly-empty directories can also be deleted. Then it writes log files for what it did.

Prerequisites:
7-zip must be installed on your computer, in the default directory. It checks for both the 64 and 32 bit versions of 7-zip, so either can be installed. http://www.7-zip.org/
You also might need to update to at least v3 of PowerShell through Windows Update. v2 might work, but I can't test if it does.

Options:
There are 5 options at the top of the script that can be changed to either enable or disable them. They are:
  • * Write a Testing log
    • This includes all output and 7-zip testing results. Can get very large, very fast, if testing a lot of files. My biggest run was around 1040 comics, all in separate directories, that created a 6.65MB log file.
  • * Write a Bad Comics log
    • This will write a log file of the file name(s) and path(s) of the comic(s) sent to the Recycle Bin, as well as any directories sent there.
  • * Delete Bad Comics
    • Fairly self-explanatory. This will delete any bad comics that it finds to the recycle bin.
  • * Delete Bad Comics Directory
    • Approximately the same as above, although, enabling this option won't delete the directories to the Recycle Bin if the bad comics aren't deleted.
  • * Log File Directory
    • Where you want to put the log files. In the format: C:\Path\To\Your\Directory\
Caveat:
I've only tested this script on my system (Win 7 x64 Ultimate). I don't know how/if it will work on yours. I'm using PowerShell version 3. I don't know if it will work with v1 or v2. I'm guessing that it might work with v2, but not v1. You might have to update. To find out your version of PowerShell open up a command prompt (click on Start, type cmd, hit Enter) then type or paste this in (include the quotes):

Code: Select all

powershell "get-host|Select-Object version"
and hit Enter.

To use:
Select and copy all of the code below, create a new text file somewhere, open it and paste the code in, save and close it, and rename the text file to something at least semi-intuitive with ps1 as the extension (that's a one on the end). I have mine saved as ComicChecker.ps1.
To run it:
Right-Click on the script file and select 'Run with PowerShell'

If you want to use the fancy PowerShell Integrated Scripting Environment to run or edit the script you can Right-Click on the script and click on 'Edit' and it will open in the PowerShell ISE. To run it from there click the pretty green arrow near the top.


** The Script: **

Code: Select all

## Annihilator6000's Comic Checker Script
##
## Author:  Annihilator6000
## Creation Date: August 5th, 2014
## Last Modified: August 10th, 2014
## Purpose: Recursively finds comic files in a user-selected directory and tests them with 7-zip's built-in archive testing utility.
##          Logs complete testing results, and separately logs the bad comics to a simple list.


#--------------------------------------------------------------------
# Can change these values from $true to $false to disable the setting
#--------------------------------------------------------------------
$Global:writeTestingLog    = $true
$Global:writeBadComicsLog  = $true
$Global:deleteBadComics    = $true # Deletes the bad comic files to the Recycle Bin.
$Global:deleteBadComicsDir = $true # Only deletes the Bad Comic File's parent directory if empty. Can only be enabled if
                                   # $Global:deleteBadComics is enabled as well
$Global:logFileDir         = "C:\Users\Public\Documents\" # Where to store the Testing and Removal logs - can be changed to C:\Your\Path\

#--------------------------------------------------------------------
# Don't change anything below this line
#--------------------------------------------------------------------
$Global:testOutput   = $null
$Global:testString   = "Everything is Ok"
$Global:totalOutput  = $null
$Global:infoOutput   = $null
$Global:badFilesList = $null

if($Global:deleteBadComics){
    Add-Type -AssemblyName Microsoft.VisualBasic
}


function Start-Executable {
    param(
        [String] $FilePath,
        [String[]] $ArgumentList
    )
    $process = New-Object System.Diagnostics.Process
    $process.StartInfo.FileName = $FilePath
    $process.StartInfo.Arguments = $ArgumentList
    $process.StartInfo.UseShellExecute = $false
    
    
    $process.StartInfo.RedirectStandardOutput = $true
        if ($process.Start()){
            $output = $process.StandardOutput.ReadToEnd() -replace "\r\n$",""
            if ($output){
                $Global:testOutput = $output
                $Global:totalOutput += $output + "`r`n`r`n"
            }
            $process.WaitForExit()
            & "$Env:SystemRoot\system32\cmd.exe" `/c exit $process.ExitCode
        }
}

Function Info($infoString)
{   
    $Global:infoOutput += $infoString.replace("`n","`r`n")
    return $infoString
}

"`n`n"
Info("-- Annhiliator6000's Comic Checker Script --")


$7zip64dir = "C:\Program Files\7-Zip\7z.exe"
$7zip32dir = "C:\Program Files (x86)\7-Zip\7z.exe"
$7zip=""
if(Test-Path $7zip64dir){
    $7zip=$7zip64dir
}ElseIf(Test-Path $7zip32dir){
    $7zip=$7zip32dir
}else {
    "`n7zip not installed. 7zip is needed for comic testing. Download and install 7zip."
    "Aborting comic test script."
    Pause
    Exit
}


$app = new-object -com Shell.Application
$folder = $app.BrowseForFolder(0, "Select Comics Folder", 0, "")

if(!$folder) { "`nNo comic directory selected. Aborting script."
    Pause
    Exit }


$INCLUDE=@("*.cbz","*.cbr")
$comicFiles = Get-Childitem $folder.Self.Path -Name -Recurse -Include $INCLUDE


$folderPath = $folder.Self.Path
if(!$comicFiles) {
    "`nNo Comics to test in: $folderPath Aborting script."
    Pause
    Exit }

Info("`n`n-Testing log file will$(if(!$Global:writeTestingLog) {" not"}) be created" +
"`n-Bad comics log file will$(if(!$Global:writeBadComicsLog) {" not"}) be created" +
"`n-Bad comics will$(if(!$Global:deleteBadComics) {" not"}) be deleted" +
"`n-Empty directories will$(if(!($Global:deleteBadComicsDir -and $Global:deleteBadComics)) {" not"}) be deleted" +
"`n-Log file directory: $Global:logFileDir")

Info("`n`nNow testing comics in $folderPath`nKey:`n`t= Good file`n`t! Bad file`n`n")


$numberTested=0
$numberBad=0
$directoriesDeleted = ""
foreach($comicFile in $comicFiles){
    ++$numberTested
    $mark = "="
    
    $fullPath = $folderPath + "\" + $comicFile
    Start-Executable "`"$7zip`" t `"$fullPath`""
    if($Global:testOutput.IndexOf($Global:testString) -eq -1){
        ++$numberBad
        $mark = "!"
        if($Global:deleteBadComics){
            $comicPathSplit = (@($fullPath.Split('\')))
            $fileNameLength = $comicPathSplit[-1].ToString().Length
            $folderParent = (Get-Item $fullPath).FullName.Substring(0, $fullPath.Length - $fileNameLength)
            $checkParentFiles = Get-Childitem $folderParent -Name
            
            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullPath,'OnlyErrorDialogs','SendToRecycleBin')

	        if($Global:deleteBadComicsDir){
                if($checkParentFiles -is [String]){
                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($folderParent,'OnlyErrorDialogs','SendToRecycleBin')
                    $directoriesDeleted += $folderParent + "`r`n"
                }
            }
        }
        $Global:badFilesList += $fullPath += "`r`n"
    }
    
    

    if ($numberTested % 100 -eq 0){
        $info = Info("$mark`n$numberTested comics tested`n")
        Write-Host -NoNewline $info
    }
    elseif ($numberTested % 50 -eq 0){
        $info = Info("$mark`n")
        Write-Host -NoNewline $info
    }
    else{
        $info = Info("$mark")
        Write-Host -NoNewline $info
    }
    $Global:totalOutput += "`r`n" + $mark + "`r`n"
}


$sTime = Get-Date -Format s
$sTime = $sTime.Replace(':','.')


Info("`n`n---------------------------------------------------------`n`nNumber of comics tested: $numberTested`nNumber of bad comics: $numberBad")


if($Global:writeTestingLog){
    $logFileName = $Global:logFileDir + "comicTestingLog_$sTime.txt"
    Info("`nComic Testing Log File: " + $logFileName + "`n")
    Info("`n---------------------------------------------------------`n")
    $Global:infoOutput += "`r`nTesting Information:`r`n`r`n"
    $Global:totalOutput = $Global:infoOutput + $Global:totalOutput
    $Global:totalOutput | Out-File $logFileName
}

if($numberBad -igt 0){
    $badMessage = "Bad comic file(s) found:"
    if($Global:deleteBadComics){
        $badMessage = "Bad comic file(s) sent to Recycle Bin:"
    }

    Info("`n---------------------------------------------------------`n`n$badMessage`n$Global:badFilesList")
    Info("Empty directories sent to Recycle Bin:`n$directoriesDeleted")

    if($Global:writeBadComicsLog){
        $Global:badFilesList = $badMessage + "`r`n" + $Global:badFilesList
        $Global:badFilesList += "`r`n`r`nEmpty directories sent to Recycle Bin:`r`n$directoriesDeleted"
        $badFileLog = $Global:logFileDir + "comicRemovalLog_$sTime.txt"
        $Global:badFilesList | Out-File $badFileLog
        Info("Bad Comic Removal Log File: $badFileLog")
    }
}
"`n"
Pause
"`n"
The Aftermath:
The log files that it creates by default are:
  • C:\Users\Public\Documents\comicTestingLog_2014-08-10T23.41.57.txt
and
  • C:\Users\Public\Documents\comicRemovalLog_2014-08-10T23.41.57.txt
They're in the format name_YYYY-MM-DDTHH.MM.SS.txt


Example output to the console window (and the top half to the top of the Testing Log, and the bottom half to the Bad Comics Log) would be:

Code: Select all

-- Annhiliator6000's Comic Checker Script --


-Testing log file will be created
-Bad comics log file will be created
-Bad comics will be deleted
-Empty directories will be deleted
-Log file directory: C:\Users\Public\Documents\


Now testing comics in C:\Comics Test
Key:
	= Good file
	! Bad file


=!!!=!!=

---------------------------------------------------------

Number of comics tested: 8
Number of bad comics: 5

Comic Testing Log File: C:\Users\Public\Documents\comicTestingLog_2014-08-10T23.41.57.txt


---------------------------------------------------------


---------------------------------------------------------

Bad comic file(s) sent to Recycle Bin:
C:\Comics Test\Red Sonja 003(2005)(Digital)(TLK-EMPIRE-HD).cbr
C:\Comics Test\Red Sonja 004(2005)(Digital)(TLK-EMPIRE-HD).cbr
C:\Comics Test\Savage_Dragon_v2_150__2009___oddBot-DCP_.cbz
C:\Comics Test\Red Sonja 033(2005)(Digital)(TLK-EMPIRE-HD)\Red Sonja 033(2005)(Digital)(TLK-EMPIRE-HD).cbr
C:\Comics Test\savagedragon\Savage_Dragon_v2_150__2009___oddBot-DCP_.cbz

Empty directories sent to Recycle Bin:
C:\Comics Test\Red Sonja 033(2005)(Digital)(TLK-EMPIRE-HD)\
C:\Comics Test\savagedragon\

Bad Comic Removal Log File: C:\Users\Public\Documents\comicRemovalLog_2014-08-10T23.41.57.txt


Press Enter to continue...: 
Methanoid
Posts: 66
Joined: Wed Jun 10, 2015 9:10 pm

Re: [Windows] Annhiliator6000's Comic Checker Script

Post by Methanoid »

My suggestions for possible improvements offered on another project apply to this too....

http://forum.mylarcomics.com/viewtopic.php?f=6&t=531

:D
Post Reply