我正在寻找一种通过Powershell替换Word文档中文本的方法。 通过在normal.dot(所有文档)中使用宏,并使用powershell脚本传递查找和替换文本。
宏
Sub Machine()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = $Text
.Replacement.Text = $ReplaceText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
Powershell脚本
$Desktop = [Environment]::GetFolderPath("Desktop")
$Document = "$Desktop\HL2532-00E.docx"
$Text = "2532-00"
$ReplaceText = "2532-35"
$Word = New-Object -ComObject Word.Application
$Document = $Word.Documents.Open("$Document")
$Word.Run("Machine")
$Document.Save()
$Word.Quit()
$a=[System.Runtime.InteropServices.Marshal]::ReleaseComObject($Word)
答案 0 :(得分:0)
您没有在宏中定义任何变量。您必须将其更新为以下内容:
Sub Machine(FindText,ReplaceText)
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = FindText
.Replacement.Text = ReplaceText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
然后,当您从PowerShell调用它时,只需在宏名称后添加这些参数:
$Word.Run("Machine",$Text,$ReplaceText)
或者您可以跳过宏,而仅使用Find.Execute()
方法(已记录here)在PowerShell中完成所有操作。
$Document = "$home\Desktop\HL2532-00E.docx"
$Text = "2532-00"
$ReplaceText = "2532-35"
$Word = new-object -ComObject Word.Application
$Document = $Word.Documents.Open($Document)
$Find = $Document.Content.Find
$Find.ClearFormatting()|out-null
$Find.Execute($Text, $false, $false, $false, $false, $false, $true, 1, $false, $ReplaceText, 2)
$Document.Save()
$Word.Quit()
$a=[System.Runtime.InteropServices.Marshal]::ReleaseComObject($Word)
Execute
方法的语法是:
Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace)
其中大多数是$true
/ $false
,其中FindText
和ReplaceWith
是字符串。两个奇数分别是Wrap
和Replace
,它们是枚举,其中1 = wdFindContinue和2 = wdReplaceAll。您可以在上面链接的页面上找到这些枚举的链接。