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


# Устанавливаем кодировку, чтобы в консоли были видны русские буквы
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# ЭТА СТРОЧКА ГЛАВНАЯ: она говорит скрипту работать в той папке, где он запущен
Set-Location $PSScriptRoot

$csvPath = "data.csv"
$downloadDir = "downloads"
$baseUrl = "https://main.atb.su/normdocs/Lists/Docs/ByCategory.aspx"
$baseDomain = "https://main.atb.su"

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

Write-Host "--- Скрипт запущен в папке: $(Get-Location) ---" -ForegroundColor Yellow

if (!(Test-Path $csvPath)) {
    Write-Host "!!! ОШИБКА: Не вижу файл $csvPath в этой папке !!!" -ForegroundColor Red
    Read-Host "Нажмите Enter, чтобы выйти"
    exit
}

# Читаем данные (разделитель точно ";" так как это экселевский CSV)
$data = Import-Csv -Path $csvPath -Delimiter ";" -Encoding UTF8

foreach ($row in $data) {
    $title = $row."Название"
    $category = $row."Категория"
    if (-not $title) { continue }

    Write-Host "`nИщу: $title..." -ForegroundColor Cyan

    $escTitle = [uri]::EscapeDataString($title)
    $escCat = [uri]::EscapeDataString($category)
    $searchUrl = "$baseUrl?FilterField1=Title&FilterValue1=$escTitle&FilterField2=DocCategory&FilterValue2=$escCat"

    try {
        # Используем ваши системные доступы (NTLM)
        $page = Invoke-WebRequest -Uri $searchUrl -UseDefaultCredentials -TimeoutSec 15
        
        if ($page.Content -match 'href="([^"]*?Attachments/[^"]+)"') {
            $fileUrl = "$baseDomain$($matches[1])"
            $fileName = [System.Web.HttpUtility]::UrlDecode($fileUrl.Split('/')[-1])
            $savePath = Join-Path $downloadDir $fileName

            if ($page.Content -match "Действителен") {
                Write-Host "  [+] Найдено! Скачиваю: $fileName" -ForegroundColor Green
                Invoke-WebRequest -Uri $fileUrl -OutFile $savePath -UseDefaultCredentials
            } else {
                Write-Host "  [!] Пропуск: статус не 'Действителен'" -ForegroundColor Yellow
            }
        } else {
            Write-Host "  [-] Файл не найден на странице SharePoint." -ForegroundColor Red
        }
    } catch {
        Write-Host "  [!] Ошибка сети/доступа: $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host "`n--- Готово! Проверьте папку 'downloads' ---" -ForegroundColor White
Read-Host "Нажмите Enter, чтобы закрыть окно"