gpt4 book ai didi

powershell - 如何替换文件夹中 Word 文档中所有出现的字符串

转载 作者:行者123 更新时间:2023-12-04 18:22:42 42 4
gpt4 key购买 nike

我设法找到并编辑每个单词文件。使用此代码:

$objWord = New-Object -comobject Word.Application  
$objWord.Visible = $false

$objDoc = $objWord.Documents.Open("C:\users\stefan\test\New Microsoft Word Document.docx")
$objSelection = $objWord.Selection

$FindText = "that"
$MatchCase = $False
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdReplaceNone = 0
$ReplaceWith = "this"
$wdFindContinue = 1

$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith)
$objDoc.Save()
$objWord.Quit()

但我想为整个文件夹做这件事。我试图插入这样的东西:
$objWord = New-Object -comobject Word.Application  
$objWord.Visible = $false

$list = Get-ChildItem "c:\users\stefan\test\*.*" -Include *.doc*
foreach($item in $list){
$objDoc = $objWord.Documents.Open($list.FullName,$true)

$objSelection = $objWord.Selection

$FindText = "Sara"
$MatchCase = $False
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdReplaceNone = 0
$ReplaceWith = "AJMOO"
$wdFindContinue = 1

$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith)
$objDoc.Save()
$objWord.Quit()
}

此外,它只更改找到的一项,但我想要文件中的所有项目。
谢谢。

最佳答案

多次更换

Also, it changes only one item that is found, but I want all items in the file



这是因为您尚未将替换范围设置为所有项目。来自您未在 Execute method call 中指定的下一个参数.设置一个名为 $wdReplaceAll and set it to 2 的变量.然后调整调用以添加该变量。
$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ` 
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$wdReplaceAll)

这解决了针对一个文件运行时的问题。

多个文件

But I want to do it for whole folder



部分问题是您没有正确查询文件夹中的文件。 -Include-Recurse 合作时很挑剔和工作但是你把它当作 -Filter反正这样调整。
$list = Get-ChildItem "c:\users\stefan\test\" -filter "*.doc*"

接下来,当您循环时,您在调用 .open() 时不使用当前迭代而是使用整个集合。
$objDoc = $objWord.Documents.Open($list.FullName,$true)

应该是
$objDoc = $objWord.Documents.Open($item.FullName,$true)

根据您的循环定义。

现在您需要确保在退出应用程序之前关闭每个文档。现在你正在退出循环内的单词。
foreach($item in $list){
#.... Stuff and things happens here.
$objDoc.Save()
$objDoc.Close()
}

$objWord.Quit()

变量声明和调用

现在你设置 $wrap到变量 $wdFindContinue 的值.当它第一次被调用时 $wdFindContinue为空,因为它没有在代码后面的几行中设置。
$Wrap = $wdFindContinue 
#...
$wdFindContinue = 1

切换这些行的顺序或只是设置 $wrap直接到 1. 我不确定这不正确的含义。

关于powershell - 如何替换文件夹中 Word 文档中所有出现的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552217/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com