提问人:Siim Bachmann 提问时间:11/1/2023 更新时间:11/2/2023 访问量:48
使用 Powershell 批量编辑(查找和替换)docx 文件及其页脚和页眉
Mass editing (find and replace) docx files and its footer and header with Powershell
问:
我正在尝试使用 Powershell 创建一个脚本来批量编辑文件夹中的 docx 文件。在这种情况下,我试图让他们将字符串“154”替换为“12”。它可以工作,但它不会编辑文档的页脚。我怎样才能修改我的代码,让它也能这样做?
$Word = New-Object -ComObject Word.Application
# Search for all Word document types (.doc, .docx, .doct, etc.)
$WordFiles = Get-ChildItem -Recurse | ? Name -like "*.do[c,t]*"
$FindText = "154" # <= Find this text
$ReplaceText = "12" # <= Replace it with this text
$MatchCase = $false
$MatchWholeWorld = $true
$MatchWildcards = $false
$MatchSoundsLike = $false
$MatchAllWordForms = $false
$Forward = $false
$Wrap = 1
$Format = $false
$Replace = 2
foreach($WordFile in $WordFiles) {
# Open the document
$Document = $Word.Documents.Open($WordFile.FullName)
# Find and replace the text using the variables we just setup
$Document.Content.Find.Execute($FindText, $MatchCase, $MatchWholeWorld, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $Replace)
# Save and close the document
$Document.Close(-1) # The -1 corresponds to https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveoptions
}
答:
0赞
kconsiglio
11/2/2023
#1
马蒂亚斯的评论是正确的。遍历并使用每个操作将编辑页眉/页脚以及文档中的文本。$Document.StoryRanges
Find.Execute
StoryRange
foreach($WordFile in $WordFiles) {
# Open the document
$Document = $Word.Documents.Open($WordFile.FullName)
# Find and replace the text using the variables we just setup
foreach ($story in $Document.StoryRanges){
$story.Find.Execute($FindText, $MatchCase, $MatchWholeWorld, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $Replace)
}
# Save and close the document
$Document.Close(-1) # The -1 corresponds to https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveoptions
}
评论
$Document.StoryRanges