我想替换FieldCodes(Word文档)中的文本。我该如何使用变量?
这是针对具有链接到其他Word Doc的Word Doc(IncludeText链接)的。当我一一更改链接而没有变量时,它起作用。当我使用变量时,它不会。
$Desktop = [Environment]::GetFolderPath("Desktop")
$Word = New-Object -ComObject Word.Application
$Document = $Word.Documents.Open("$Desktop\Test.docx")
$Test = 147 # (Test.GetType() = Int32)
$Document.Fields(147) #Works
$Document.Fields($Test) #Works
$Document.Fields($Test).LinkFormat.SourceFullName = "" #Works
$TextLinks = $Document.Fields | Where-Object Type -eq "68" | Select -expand Index
#TextLinks contains value 147 and 149
$Test = $TextLinks[0] # is also 147 (Test.GetType() = Int32)
$Document.Fields($Test) #Doesn't work (runs indefinitely)
$Document.Fields($Test).LinkFormat.SourceFullName = "" #Doesn't work (runs indefinitely)
147..149 | Foreach { $Document.Fields($_).LinkFormat.SourceFullName } #Doesn't work (runs indefinitely)
更新:
现在它与$Test = [INT]$Textlinks[0]
一起运行。谢谢辛迪!
但是当我尝试循环时,它会挂第二个值
$Desktop = [Environment]::GetFolderPath("Desktop")
$Word = New-Object -ComObject Word.Application
$Document = $Word.Documents.Open("$Desktop\Test.docx")
$TextLinks = $Document.Fields | Where-Object Type -eq "68" | Select -expand Index
$ItemNumber = 0
$End = $TextLinks.Count
Do {
$Item = [INT]$Textlinks[$ItemNumber]
if ($Document.Fields($Item).LinkFormat.SourceFullName -match "Test") {
$Link = $Document.Fields($Item).LinkFormat.SourceFullName -replace "Test", "TestTest"
$Document.Fields($Item).LinkFormat.SourceFullName = $Link
$Document.Fields($Item).LinkFormat.AutoUpdate = "True"
$ItemNumber += 1
}
} Until ($ItemNumber -eq $End)
$Document.Save()
$Word.Quit()
$OUT=[System.Runtime.InteropServices.Marshal]::ReleaseComObject($Word)
更新2:
下面的代码运行正常,但我不明白为什么上面的代码不
$Desktop = [Environment]::GetFolderPath("Desktop")
$Word = New-Object -ComObject Word.Application
$Document = $Word.Documents.Open("$Desktop\Test.docx")
$TextLinks = $Document.Fields | Where-Object Type -eq "68" | Select -expand Index
$ItemNumber = ($TextLinks.Count)-1
$End = -1
Do {
$Item = [INT]$Textlinks[$ItemNumber]
if ($Document.Fields($Item).LinkFormat.SourceFullName -match "Test") {
$Link = $Document.Fields($Item).LinkFormat.SourceFullName -replace "Test", "TestTest"
$Document.Fields($Item).LinkFormat.SourceFullName = $Link
$Document.Fields($Item).LinkFormat.AutoUpdate = "True"
$ItemNumber -= 1
}
} Until ($ItemNumber -eq $End)
$Document.Save()
$Word.Quit()
$OUT=[System.Runtime.InteropServices.Marshal]::ReleaseComObject($Word)