-1
我想用我的.docx文件中的某些單詞替換另一個.txt文件中的某些字符串通過Powershell。 我打開,並嘗試與兩個功能來代替的話:用Powershell代替.docx文件中的很多單詞
Function OpenWordDoc($Filename)
{
$objWord = New-Object -comobject Word.Application
$objWord.Visible = $True;
$objWord.Documents.Open($Filename)
$objSelection = $objWord.Selection
Return $objSelection; #return objWord
}
Function SearchAWord($Document,$search,$replacewithtext)
{
$FindText = $search
$MatchCase = $False
$MatchWholeWord = $False
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdReplaceNone = 1
$ReplaceWith = $replacewithtext
$wdFindContinue = 1
$a=$Document.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceNone)
}
當我打開文件與功能,並嘗試用它工作的字符串替換詞,但是當我試圖去改變更多的話它沒有找到具有該功能的其他單詞。 當我在打開文檔後直接搜索它們時,我可以找到它們。所以腳本只能找到搜索到的第一個單詞。
我是否創建了錯誤的函數?
編輯:我打電話的功能是這樣的:
$doc=OpenWordDoc -Filename "C:\Users\$UserName\Desktop\test.docx"; #opens the Word-doc
for([int]$i=0; $i -ne 4;$i++)
{
SearchAWord -Document $doc -search "string$i" -replacewithtext "test$i"
}
你是如何調用'SearchAWord'您可以加入這個代碼? – Richard
@Richard在main-post中添加了對這兩個函數的調用 – Paxz