Created
July 18, 2025 08:42
-
-
Save eugrus/88261bca03cb4175d738b167f60a4caf to your computer and use it in GitHub Desktop.
Replace double paragraph breaks with single ones in an open MS Word document.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Скрипт для замены двойных переводов абзаца на одинарные в открытом документе MS Word | |
# Функция для подключения к Word | |
function Connect-ToWord { | |
try { | |
# Попытка подключиться к уже запущенному экземпляру Word | |
$word = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Word.Application") | |
Write-Host "Interop connection..." -ForegroundColor Green | |
return $word | |
} | |
catch { | |
Write-Host "Connection to Word failed :(" -ForegroundColor Red | |
return $null | |
} | |
} | |
# Функция для замены двойных переводов строк | |
function Replace-DoubleLineBreaks { | |
param( | |
[Parameter(Mandatory=$true)] | |
$WordApp | |
) | |
try { | |
# Получаем активный документ | |
$doc = $WordApp.ActiveDocument | |
if (-not $doc) { | |
Write-Host "No active document" -ForegroundColor Red | |
return $false | |
} | |
Write-Host "Parsing $($doc.Name)" -ForegroundColor Yellow | |
# Получаем объект Range для всего документа | |
$range = $doc.Content | |
# Настраиваем параметры поиска и замены | |
$findObject = $range.Find | |
$findObject.ClearFormatting() | |
$findObject.Replacement.ClearFormatting() | |
# Параметры поиска | |
$findObject.Text = "^p^p" # Два перевода абзаца | |
$findObject.Replacement.Text = "^p" # Один перевод абзаца | |
$findObject.Forward = $true | |
$findObject.Wrap = 1 # wdFindContinue | |
$findObject.Format = $false | |
$findObject.MatchCase = $false | |
$findObject.MatchWholeWord = $false | |
$findObject.MatchWildcards = $false | |
$findObject.MatchSoundsLike = $false | |
$findObject.MatchAllWordForms = $false | |
# Выполняем замену | |
$replacementCount = 0 | |
# Заменяем все вхождения | |
while ($findObject.Execute()) { | |
$findObject.Replacement.Text = "^p" | |
$range.Find.Execute($findObject.Text, $false, $false, $false, $false, $false, $true, 1, $false, $findObject.Replacement.Text, 2) # wdReplaceAll = 2 | |
$replacementCount++ | |
break # Выходим из цикла, так как ReplaceAll заменил все сразу | |
} | |
# Альтернативный способ подсчета замен | |
$result = $range.Find.Execute($findObject.Text, $false, $false, $false, $false, $false, $true, 1, $false, $findObject.Replacement.Text, 2) | |
if ($result) { | |
Write-Host "Double breaks removed" -ForegroundColor Green | |
} else { | |
Write-Host "No double breaks found" -ForegroundColor Yellow | |
} | |
return $true | |
} | |
catch { | |
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red | |
return $false | |
} | |
} | |
# Функция для безопасного завершения работы | |
function Disconnect-FromWord { | |
param($WordApp) | |
try { | |
# Освобождаем COM-объект | |
if ($WordApp) { | |
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($WordApp) | Out-Null | |
} | |
# Принудительная сборка мусора | |
[System.GC]::Collect() | |
[System.GC]::WaitForPendingFinalizers() | |
Write-Host "COM object releazed" -ForegroundColor Green | |
} | |
catch { | |
Write-Host "COM exception: $($_.Exception.Message)" -ForegroundColor Yellow | |
} | |
} | |
# Основная функция | |
function Main { | |
# Подключаемся к Word | |
$wordApp = Connect-ToWord | |
if (-not $wordApp) { | |
Write-Host "COM connection to Word failed." -ForegroundColor Red | |
return | |
} | |
try { | |
# Показываем информацию о документе | |
$activeDoc = $wordApp.ActiveDocument | |
Write-Host "Active document: $($activeDoc.Name)" -ForegroundColor Yellow | |
Write-Host "Path: $($activeDoc.FullName)" -ForegroundColor Yellow | |
Write-Host "" | |
Replace-DoubleLineBreaks -WordApp $wordApp | |
} | |
finally { | |
# Отключаемся от Word | |
Disconnect-FromWord -WordApp $wordApp | |
} | |
} | |
# Запуск основной функции | |
Main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment