Загрузка данных


[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
Set-Location $PSScriptRoot

# =====================================================================
# НАСТРОЙКИ
# =====================================================================
# Вставь сюда ту самую длинную ссылку, которую ты нашла
$startUrl = "https://main.atb.su/normdocs/Lists/Docs/ByCategory.aspx?C=6&p_RegDate=20231219%2015%3a00%3a00&p_Created=20231225%2004%3a44%3a04&RootFolder=%2fnormdocs%2fLists%2fDocs%2fpub&PageFirstRow=1&FilterField1=DocCategoryId&FilterValue1=6&View={71C6C749-C001-4601-B766-36AFFD10DEE8}"

# Имя папки, куда всё упадет
$downloadDir = "All_Active_Docs"
# =====================================================================

if (!(Test-Path $downloadDir)) { New-Item -ItemType Directory -Path $downloadDir | Out-Null }

$uri = [System.Uri]$startUrl
$baseDomain = "$($uri.Scheme)://$($uri.Host)"
$currentUrl = $startUrl
$pageNum = 1

Write-Host "=== ЗАПУСК: СКАЧИВАНИЕ ВСЕХ ДЕЙСТВИТЕЛЬНЫХ ДОКУМЕНТОВ ===" -ForegroundColor Cyan
Write-Host "Папка назначения: $downloadDir" -ForegroundColor Gray

while ($currentUrl) {
    Write-Host "`n[ Страница $pageNum ] Читаю список..." -ForegroundColor Yellow
    
    try {
        $page = Invoke-WebRequest -Uri $currentUrl -UseDefaultCredentials -TimeoutSec 30
    } catch {
        Write-Host "  [!] Ошибка доступа. Возможно, нужно обновить страницу в браузере." -ForegroundColor Red
        break
    }

    # Ищем строки таблицы
    $rows = [regex]::Matches($page.Content, '(?is)<tr[^>]*class="[^"]*ms-itmhover[^"]*"[^>]*>(.*?)</tr>')
    
    $count = 0
    foreach ($row in $rows) {
        $rowHtml = $row.Groups[1].Value
        
        # ГЛАВНОЕ УСЛОВИЕ: только если статус "Действителен"
        if ($rowHtml -match "Действителен") {
            
            # Ищем ссылку на файл (pdf, doc, docx, xlsx)
            if ($rowHtml -match 'href="([^"]*?Attachments/[^"]+)"' -or $rowHtml -match 'href="([^"]+?\.(pdf|docx?|xlsx?|rtf))"') {
                $link = [System.Web.HttpUtility]::HtmlDecode($matches[1])
                
                $fileUrl = if ($link -match "^http") { $link } else { "$baseDomain$($link.StartsWith('/') ? "" : "/")$link" }
                $fileName = [System.Web.HttpUtility]::UrlDecode($fileUrl.Split('/')[-1])
                
                # Убираем символы, которые Windows не любит в именах файлов
                $fileName = $fileName -replace '[\\\/\:\*\?\"\<\>\|]', '_'
                $savePath = Join-Path $downloadDir $fileName

                if (-not (Test-Path $savePath)) {
                    Write-Host "  [+] Качаю: $fileName" -ForegroundColor Green
                    try {
                        Invoke-WebRequest -Uri $fileUrl -OutFile $savePath -UseDefaultCredentials
                        $count++
                    } catch {
                        Write-Host "  [!] Ошибка при сохранении $fileName" -ForegroundColor Red
                    }
                }
            }
        }
    }
    
    Write-Host "Обработано на странице: $count" -ForegroundColor Gray

    # Ищем ссылку на следующую страницу (кнопка "Далее")
    if ($page.Content -match 'href="([^"]*?Paged=TRUE[^"]+?)"') {
        $nextLink = [System.Web.HttpUtility]::HtmlDecode($matches[1])
        
        if ($nextLink.StartsWith("?")) {
            $currentUrl = ($currentUrl.Split('?')[0]) + $nextLink
        } else {
            $currentUrl = if ($nextLink -match "^http") { $nextLink } else { "$baseDomain$nextLink" }
        }
        $pageNum++
        Start-Sleep -Milliseconds 500 # Небольшая пауза для стабильности
    } else {
        Write-Host "`n--- Все доступные страницы пройдены! ---" -ForegroundColor White
        $currentUrl = $null
    }
}

Write-Host "Готово! Ищи файлы в папке script/$downloadDir" -ForegroundColor Cyan
Read-Host "Enter, чтобы выйти"