[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# Определяем пути
$scriptPath = $PSScriptRoot
if (!$scriptPath) { $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition }
$oldDir = Join-Path $scriptPath "Old_Doc_Files"
$convertedDir = Join-Path $scriptPath "Converted_Docx_Files"
# Проверки
if (!(Test-Path $oldDir)) { Write-Host "[!] Папка Old_Doc_Files не найдена!" -ForegroundColor Red; exit }
if (!(Test-Path $convertedDir)) { New-Item -ItemType Directory -Path $convertedDir | Out-Null }
$files = Get-ChildItem -Path $oldDir -Filter "*.doc"
if ($files.Count -eq 0) { Write-Host "Нет файлов .doc в Old_Doc_Files." -ForegroundColor Yellow; exit }
Write-Host "Найдено файлов: $($files.Count). Начинаю конвертацию..." -ForegroundColor Cyan
try {
$word = New-Object -ComObject Word.Application
$word.Visible = $false
$i = 0
foreach ($file in $files) {
$i++
# Формируем путь и принудительно делаем его строкой [string]
$newFileName = $file.BaseName + ".docx"
$newPath = [string](Join-Path $convertedDir $newFileName)
Write-Host "[$i/$($files.Count)] Конвертирую: $($file.Name)" -ForegroundColor White
try {
$doc = $word.Documents.Open($file.FullName)
# Используем SaveAs2 и передаем параметры без [ref], так проще для COM
# 16 — это wdFormatXMLDocument (стандартный .docx)
$doc.SaveAs2($newPath, 16)
$doc.Close()
} catch {
Write-Host " [!] Ошибка в файле $($file.Name): $($_.Exception.Message)" -ForegroundColor Red
}
}
Write-Host "`n--- ГОТОВО! ---" -ForegroundColor Green
Write-Host "Результат тут: $convertedDir"
} catch {
Write-Host "`n[!] Критическая ошибка: $($_.Exception.Message)" -ForegroundColor Red
} finally {
if ($word) {
$word.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word)
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
}
}
Read-Host "`nНажми Enter"