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


[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
Add-Type -AssemblyName System.Web

# Настройки
$url = "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}"
$dir = "Downloads_Bank_Docs"

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

# Правильный базовый путь для вложений SharePoint
$basePath = "https://main.atb.su/normdocs/Lists/Docs/"

Write-Host "`n--- Начинаю выкачивать файлы ---" -ForegroundColor Cyan

try {
    $page = Invoke-WebRequest -Uri $url -UseDefaultCredentials -TimeoutSec 30 -UseBasicParsing
    $rows = [regex]::Matches($page.Content, '(?is)<tr[^>]*>(.*?)</tr>')
    
    foreach ($row in $rows) {
        $html = $row.Groups[1].Value
        
        if ($html -match "Действителен") {
            # Ищем ссылку (она может начинаться с Attachments/ или /normdocs/...)
            if ($html -match 'href="([^"]+?\.(pdf|docx?|xlsx?|rtf))"') {
                $link = [System.Net.WebUtility]::HtmlDecode($matches[1])
                
                # Собираем полный URL правильно
                if ($link.StartsWith("http")) {
                    $fullUrl = $link
                } elseif ($link.StartsWith("/")) {
                    $fullUrl = "https://main.atb.su" + $link
                } else {
                    # Если ссылка относительная (как Attachments/...), добавляем путь списка
                    $fullUrl = $basePath + $link
                }
                
                $fileName = [System.Net.WebUtility]::UrlDecode($fullUrl.Split('/')[-1])
                $fileName = $fileName -replace '[\\\/\:\*\?\"\<\>\|]', '_'
                $path = Join-Path $dir $fileName

                if (!(Test-Path $path)) {
                    Write-Host "[+] Качаю: $fileName" -ForegroundColor Green
                    try {
                        Invoke-WebRequest -Uri $fullUrl -OutFile $path -UseDefaultCredentials -TimeoutSec 60
                    } catch {
                        Write-Host "    [!] Не удалось скачать: $fileName (Ошибка: $($_.Exception.Response.StatusCode))" -ForegroundColor Yellow
                    }
                }
            }
        }
    }
    Write-Host "`n--- Готово! Проверь папку $dir ---" -ForegroundColor White
} catch {
    Write-Host "`n[!] Критическая ошибка: $($_.Exception.Message)" -ForegroundColor Red
}

Read-Host "Нажми Enter"