PowerShell:更新/刷新Word文档的TOC


0

我正在使用PowerShell脚本自动更新/刷新Word文档中的目录(之前是从不自动执行此操作的应用程序导出的)

导出文档中的TOC到达如下:

在此输入图像描述

点击(Inhaltsverzeichnis aktualisieren)它会正确生成目录。

但是,我希望使用PowerShell自动执行此操作并提出以下脚本(请注意,我是PowerShell的初学者):

$latestFile = Get-ChildItem -Path C:\ExportedDocuments -File -Filter "*.docx" | Sort-Object LastAccessTime -Descending | Select-Object -First 1     
$word = New-Object -ComObject Word.Application
$word.Visible=$true
$doc=$word.Documents.Open($latestFile.FullName)
$toc = $latestFile.TablesOfContents
$toc.Update()
$latestFile.save()
$latestFile.close()

我收到以下错误 - 但我不完全理解,我也不知道如何解决它们:

You cannot call a method on a null-valued expression. At line:6 char:1
+ $toc.Update()
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull   Method invocation failed because [System.IO.FileInfo] does not contain a method named 'save'. At line:7 char:1
+ $latestFile.save()
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound   Method invocation failed because [System.IO.FileInfo] does not contain a method named 'close'. At line:8 char:1
+ $latestFile.close()
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Answers:


1

请参阅下面修改的脚本:

$latestFile = Get-ChildItem -Path C:\ExportedDocuments -File -Filter "*.docx" | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$word = New-Object -ComObject Word.Application
$word.Visible = $true
$doc = $word.Documents.Open($latestFile.FullName)
$toc = $doc.TablesOfContents
$toc.item(1).update()
$doc.save()
$doc.close()

您遇到的第一个问题是您将文档分配给对象$ doc,然后在下一行尝试再次直接调用文档而不是引用对象$ doc:

$doc = $word.Documents.Open($latestFile.FullName)
$toc = $latestFile.TablesOfContents

第二个问题是其他用户提到的,您需要引用要更新的ToC:

$toc.item(1).update()

1

人们可以有多个表小号内容,这就是为什么这叫做表小号 OfContents。

你应该用TablesOfContents(1).Update()

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.