我正在尝试将 Word 文档转换为替代格式。预先存在的目录 (TOC) 会产生问题。因为有近百个左右的文档,所以我想使用powershell来迭代文件并清除TOC。有一些帖子介绍如何使用 powershell insert 和 update TOC。一篇文章建议以这种方式进行,这部分有效。
$filename = "example.docx"
#create object
$word = New-Object -ComObject Word.Application
#watch changes
$word.Visible = $true
#open doc
$doc = $word.documents.open($filename)
$doc.TablesOfContent.Item(1).Delete()
$doc.save()
$doc.close()
问题是目录是空的,但仍然存在,带有“目录”标题和阴影框。 Microsoft 确实在其
网站上用 VBA 记录了
TablesOfContents
对象。努力寻求更完整的解决方案。
请尝试一下。
$filename = "D:\temp\example.docx"
#create object
$word = New-Object -ComObject Word.Application
#watch changes
$word.Visible = $true
#open doc
$doc = $word.documents.open($filename)
$doc.TablesOfContents.Item(1).Delete()
foreach ($para in $doc.Paragraphs) {if ($para.Range.Text -match "Contents") {$para.Range.Delete()}}
$doc.save()
$doc.close()