# Configuration [int] $schedule = $ENV:SCHEDULE [string] $qbtHost = $ENV:QBTHOST [string] $qbtPort = $ENV:QBTPORT [string] $qbtUser = $ENV:QBTUSER [string] $qbtPassword = $ENV:QBTPASSWORD [string] $notificationWebhookURL = $ENV:NOTIFICATIONWEBHOOKURL [string[]] $excludedTrackers = $ENV:EXCLUDEDTRACKERS -split ',' # Function to authenticate and get a session function Get-QBittorrentSession { $qbtHeaders = @{ Referer = "https://$($qbtHost):$($qbtPort)" } $qbtBody = @{ username = $qbtUser password = $qbtPassword } $qbtSession = [Microsoft.PowerShell.Commands.WebRequestSession]::new() $qbtResponse = Invoke-WebRequest -Uri "https://$($qbtHost):$($qbtPort)/api/v2/auth/login" -WebSession $qbtSession -Method POST -Headers $qbtHeaders -Body $qbtBody return $qbtSession } # Function to check if the session is valid function Test-QBittorrentSession { param ( [Microsoft.PowerShell.Commands.WebRequestSession]$session ) try { $qbtResponse = Invoke-WebRequest -Uri "https://$($qbtHost):$($qbtPort)/api/v2/app/version" -WebSession $session -Method GET -ErrorAction Stop return $true } catch { return $false } } # Function to get all torrents function Get-Torrents { param ( [Microsoft.PowerShell.Commands.WebRequestSession]$session ) $qbtResponse = Invoke-WebRequest -Uri "https://$($qbtHost):$($qbtPort)/api/v2/torrents/info" -WebSession $session -Method GET return $qbtResponse.Content | ConvertFrom-Json } # Function to delete a torrent function Remove-Torrent { param ( [Microsoft.PowerShell.Commands.WebRequestSession]$session, [string]$name, [string]$hash ) $qbtHeaders = @{ Referer = "https://$($qbtHost):$($qbtPort)" } $qbtBody = @{ hashes = $hash deleteFiles = 'true' } $qbtResponse = Invoke-WebRequest -Uri "https://$($qbtHost):$($qbtPort)/api/v2/torrents/delete" -WebSession $session -Method POST -Headers $qbtHeaders -Body $qbtBody if ($notificationWebhookURL) { $headers = @{ "Content-Type"="application/json" } $body = @{ content="Removed torrent $name with hash $hash" } $json = $body | ConvertTo-Json Invoke-WebRequest -URI $notificationWebhookURL -Method post -Body $json -Headers $headers } } # Main script $session = Get-QBittorrentSession while ($true) { if (-not (Test-QBittorrentSession -session $session)) { $session = Get-QBittorrentSession } $torrents = Get-Torrents -session $session foreach ($torrent in $torrents) { if ($torrent.state -eq 'uploading' -or $torrent.state -like "*UP") { # Check if any of the excluded trackers are in the torrent's tracker list if ($torrent.tracker -match "https?://([^/]+)") { $trackers = $matches[1] } else { $trackers = @() } if (-not ($trackers | Where-Object { $excludedTrackers -contains $_ })) { # Delete the torrent Write-Host "Delete: $($torrent.name) $($torrent.hash)" Remove-Torrent -session $session -hash $torrent.hash -name $torrent.name } } } Write-Host "Sleeping for $schedule minutes..." Start-Sleep ($schedule * 60) }