Skip to content

Instantly share code, notes, and snippets.

@The-Running-Dev
Last active February 10, 2024 14:32
Show Gist options
  • Save The-Running-Dev/19a768593544e348ece91cdf5677e42e to your computer and use it in GitHub Desktop.
Save The-Running-Dev/19a768593544e348ece91cdf5677e42e to your computer and use it in GitHub Desktop.
Scans a directory of eBooks and creates a direcory and sub directories, with hard links to the actual eBooks.
<#
Save to: Create-Kavita-Structure.ps1
and run it with: .\Create-Kavita-Structure.ps1 -sourceDir 'DriveLetter:\PathToBooks' -kavitaDir 'DriveLetter:\PathToKavitaWatchedDir"
If sourceDir is not specified, assumes current directory (.)
If kavitaDir is not specified, assumes @Kavita under the current directory (.\@Kavita)
To test this without making any changes: Create-Kavita-Structure.ps1 -whatIf
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[Parameter(Mandatory = $false)][ValidateScript( { Test-Path (Resolve-Path $_) })][string] $sourceDir = (Resolve-Path .),
[Parameter(Mandatory = $false)][ValidateScript( { Test-Path (Resolve-Path $_) })][string] $kavitaDir = (Resolve-Path '.\@Kavita')
)
# List of type level directories to exclude
$excludelist = '\@(Recycle|Kavita|Audiobookshelf|Plex)'
# Get top level directories
$directories = Get-ChildItem $sourceDir -Directory | Where-Object Name -NotMatch $excludelist
# Create the top level structure inside the Kavita directory
$directories | ForEach-Object {
$subDir = Join-Path $kavitaDir $_.Name
if ($PSCmdlet.ShouldProcess($subDir, 'Create')) {
if (-not (Test-Path $subDir -ErrorAction SilentlyContinue)) {
Write-Host "Creating Directory $subDir"
New-Item -ItemType Directory $subDir | Out-Null
}
}}
# Create the sub directories and hard links to files
$directories | `
ForEach-Object {
$subDir = Join-Path $kavitaDir $_.Name
$files = Get-ChildItem $($_.FullName) -Include *.pdf, *.epub, *.chm -File -Recurse
$files | Select-Object -First 5 | ForEach-Object {
$bookSubDirectory = Join-Path $subDir $_.BaseName
$bookSymLink = Join-Path $bookSubDirectory $_.Name
if ($PSCmdlet.ShouldProcess($bookSubDirectory, "Create Directory")) {
# Create a sub directory for the file
if (-not (Test-Path $bookSubDirectory -ErrorAction SilentlyContinue)) {
Write-Host "Creating Directory $bookSubDirectory"
New-Item -ItemType Directory $bookSubDirectory | Out-Null
}
}
if ($PSCmdlet.ShouldProcess($bookSymLink, "Create Hard Link")) {
if (-not (Test-Path $bookSymLink -ErrorAction SilentlyContinue)) {
Write-Host "Creating Hard Link $bookSymLink"
New-Item -ItemType HardLink -Path $bookSymLink -Value $_.FullName | Out-Null
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment