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:
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