2

I am working on a PowerShell-Script to update / refresh automatically the table of contents in a Word Document (which earlier was exported from an application that doesn't do that automatically)

The TOC in an exported document arrives like that:

enter image description here

On click (Inhaltsverzeichnis aktualisieren) it generates the Table of Contents properly.

However, I want this to happen automatically using PowerShell and came up with the following script (mind, that I am a beginner in 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()

Following errors I receive - but I don't completely understand and I also don't know how to fix them:

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

2 Answers 2

3

Please see your script amended below:

$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()

The 1st issue you were having is that you assigned the document to the object $doc and then on the next line tried to call the document directly again instead of referencing the object $doc:

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

The 2nd issue is as mentioned by the other user, you need to reference which ToC you want to update:

$toc.item(1).update()
0
2

One can have multiple Tables Of Contents, which is why this is called TablesOfContents.

You should use TablesOfContents(1).Update().

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .