You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PowerShell脚本实现批量替换docx文件及页脚内容?

解决PowerShell批量替换Word文档页脚内容的问题

你的脚本仅处理了文档的正文区域($Document.Content),页脚属于文档各节的独立区域,需要单独遍历处理每个节的所有页脚对象。

修改后的完整代码如下:

$Word = New-Object -ComObject Word.Application
$Word.Visible = $false # 后台运行,不显示Word窗口

# 搜索所有Word文档类型
$WordFiles = Get-ChildItem -Recurse | Where-Object Name -like "*.do[c,t]*"

$FindText = "154"
$ReplaceText = "12"

# 查找替换参数
$MatchCase = $false
$MatchWholeWord = $true # 修正原脚本变量名拼写错误
$MatchWildcards = $false
$MatchSoundsLike = $false
$MatchAllWordForms = $false
$Forward = $false
$Wrap = 1
$Format = $false
$Replace = 2

foreach($WordFile in $WordFiles) {
    $Document = $Word.Documents.Open($WordFile.FullName)
    
    # 处理正文内容
    $Document.Content.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $Replace)
    
    # 处理所有节的页脚
    foreach($Section in $Document.Sections) {
        # 遍历三种页脚类型:普通页、首页、奇偶页
        foreach($FooterType in [Microsoft.Office.Interop.Word.WdHeaderFooterIndex]::wdHeaderFooterPrimary, 
                              [Microsoft.Office.Interop.Word.WdHeaderFooterIndex]::wdHeaderFooterFirstPage,
                              [Microsoft.Office.Interop.Word.WdHeaderFooterIndex]::wdHeaderFooterEvenPages) {
            $Footer = $Section.Footers.Item($FooterType)
            # 检查页脚是否存在且可编辑
            if($Footer.Exists -and !$Footer.LinkToPrevious) {
                $Footer.Range.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $Replace)
            } elseif($Footer.Exists) {
                # 链接到前一节的页脚,仅处理第一个节的对应页脚即可
                if($Section.Index -eq 1) {
                    $Footer.Range.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $Replace)
                }
            }
        }
    }
    
    $Document.Close(-1)
}

# 释放Word COM对象,避免后台残留进程
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word) | Out-Null
Remove-Variable Word

关键修改说明:

  • 修正变量名错误:原脚本中$MatchWholeWorld拼写错误,改为$MatchWholeWord,确保整词匹配参数生效。
  • 遍历文档节与页脚:通过$Document.Sections遍历文档的每个节,针对普通页、首页、奇偶页三种页脚类型分别处理。
  • 处理链接页脚:若页脚设置为链接到前一节,仅处理第一个节的对应页脚,后续节的页脚会自动同步修改,避免重复操作。
  • 释放COM对象:脚本末尾添加释放Word对象的代码,防止后台残留Word进程占用资源。

内容的提问来源于stack exchange,提问作者Siim Bachmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:23:27