用PowerShell替换大于256个字符的Word文档的较大部分



我有一个我试图用PowerShell中的多行字符串替换占位符文本的Word文档。对于小型单行字符串来说,这很好,但是字符串参数必须小于256个字符,因此整个段落失败。

我正在使用的代码;

$objWord = New-Object -comobject Word.Application   
$objWord.Visible = $false
$objDoc = $objWord.Documents.Open("C:Usersmedocument.docx") 
$objSelection = $objWord.Selection 
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildCards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False 
$Forward = $True
$wdFindContinue = 1
$Wrap = $wdFindContinue 
$Format = $False
$wdReplaceNone = 1 
$wdReplaceAll = 2
function ProcessDocument($toFind, $toReplace, $object){   
    $shazam = $objSelection.Find.Execute($toFind,$MatchCase,$MatchWholeWord,$MatchWildCards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$toReplace,$wdReplaceAll)
}
$findText= "XXXXPLACEHOLDER"
$ReplaceWith= @"
•   The working hours of this project will be between
8:30 AM and 5:30 PM Monday through Friday, except for public holidays.
The daily rate is based on an 8-hour working day. •   Conditions
differing materially from those ordinarily encountered and generally
recognised as inherent in the work of the character provided for in
this Work Order may affect scope, schedule, services deliverables, and
fees. •   These services are provided on a Time and Materials basis.
Any timelines, dates, and/or delivery schedules provided are estimates
only and subject to change.
"@
ProcessDocument($findText,$MatchCase,$MatchWholeWord,$MatchWildCards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll)

这样做的更好的方法是什么,以便我可以替换整个部分?

这是一个快速而肮脏的解决方案,试图实现@Elomis的方法。也许这让您开始。

$chunkSize = 255 - $findText.Length
for($i = 0; $i -lt $ReplaceWith.Length - 1; $i += $chunkSize) {
    if ($ReplaceWith.Length - $i -le $chunkSize) {
        $chunk = $ReplaceWith.Substring($i, ($ReplaceWith.Length - $i))
    }
    else {
        $chunk = $ReplaceWith.Substring($i, $chunkSize) + $findText
    }
    ProcessDocument($findText,$MatchCase,$MatchWholeWord,$MatchWildCards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$chunk,$wdReplaceAll)
}

最新更新