# --- Параметры ---
$giteaUrl = "http://your-gitea-server:3000"
$owner = "owner_username"
$repo = "repo_name"
$ref = "main"
$filePath = "path/to/file.txt"
$outputFile = "C:\Downloads\file.txt"
$target = "gitea_api_token" # Имя, которое мы задали в cmdkey
# --- Достаём токен из Credential Manager ---
$token = $null
# Способ 1: Через модуль CredentialManager (если установлен)
if (Get-Module -ListAvailable -Name CredentialManager) {
Import-Module CredentialManager
$cred = Get-StoredCredential -Target $target
if ($cred) {
$token = $cred.GetNetworkCredential().Password
}
}
# Способ 2: Через прямое обращение к Windows API (работает без модулей)
if (-not $token) {
Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
[DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern bool CredReadW(string target, int type, int flags, out IntPtr credential);
[DllImport("advapi32.dll", SetLastError=true)]
public static extern void CredFree(IntPtr cred);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct CREDENTIAL {
public int Flags;
public int Type;
public string TargetName;
public string Comment;
public long LastWritten;
public int CredentialBlobSize;
public IntPtr CredentialBlob;
public int Persist;
public int AttributeCount;
public IntPtr Attributes;
public string TargetAlias;
public string UserName;
}
"@
$ptr = [IntPtr]::Zero
if ([Win32.NativeMethods]::CredReadW($target, 1, 0, [ref]$ptr)) {
try {
$c = [Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [type][Win32.NativeMethods+CREDENTIAL])
$bytes = [byte[]]::new($c.CredentialBlobSize)
[Runtime.InteropServices.Marshal]::Copy($c.CredentialBlob, $bytes, 0, $bytes.Length)
# Токен хранится в Unicode, поэтому используем Unicode.GetString
$token = [Text.Encoding]::Unicode.GetString($bytes)
}
finally { [Win32.NativeMethods]::CredFree($ptr) }
}
}
if (-not $token) {
throw "Токен '$target' не найден в Credential Manager."
}
# --- Формируем заголовок авторизации ---
# Gitea требует префикс "token" перед самим токеном в заголовке
$headers = @{
Authorization = "token $token"
}
# --- Формируем URL raw-файла ---
$apiUrl = "$giteaUrl/api/v1/repos/$owner/$repo/raw/$ref/$filePath"
# --- Скачивание ---
try {
Invoke-WebRequest -Uri $apiUrl `
-Headers $headers `
-OutFile $outputFile `
-UseBasicParsing `
-ErrorAction Stop
Write-Host "Файл успешно скачан: $outputFile" -ForegroundColor Green
}
catch {
Write-Host "Ошибка скачивания: $($_.Exception.Message)" -ForegroundColor Red
}