Created
March 30, 2026 17:56
-
-
Save eugrus/7d04033ae55a35a21d9f10d4a449da02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Word COM-Objekt holen (bereits laufende Instanz) | |
| $word = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Word.Application") | |
| $doc = $word.ActiveDocument | |
| # WdBuiltinStyle-Konstanten für Heading 1–9 | |
| $headingStyles = @( | |
| -2 # wdStyleHeading1 | |
| -3 # wdStyleHeading2 | |
| -4 # wdStyleHeading3 | |
| -5 # wdStyleHeading4 | |
| -6 # wdStyleHeading5 | |
| -7 # wdStyleHeading6 | |
| -8 # wdStyleHeading7 | |
| -9 # wdStyleHeading8 | |
| -10 # wdStyleHeading9 | |
| ) | |
| $toc = [System.Collections.ArrayList]::new() | |
| foreach ($para in $doc.Paragraphs) { | |
| $style = $para.Style | |
| $styleId = $style.NameLocal | |
| # Prüfen, ob es eine Überschriftenvorlage ist (Heading 1–9 / Überschrift 1–9) | |
| $level = -1 | |
| for ($i = 0; $i -lt $headingStyles.Count; $i++) { | |
| try { | |
| $builtinStyle = $doc.Styles.Item($headingStyles[$i]) | |
| if ($style.NameLocal -eq $builtinStyle.NameLocal) { | |
| $level = $i + 1 | |
| break | |
| } | |
| } catch { | |
| continue | |
| } | |
| } | |
| if ($level -lt 1) { continue } | |
| # ListFormat auslesen – enthält die Nummerierung aus der Vorlage | |
| $listFormat = $para.Range.ListFormat | |
| $numberText = "" | |
| if ($listFormat.ListType -ne 0) { | |
| # ListString liefert den formatierten Nummerierungstext (z.B. "1.", "1.1", "A)", "IV.") | |
| $numberText = $listFormat.ListString | |
| } | |
| # Reinen Überschriftentext (ohne Nummerierung am Anfang) | |
| $rawText = $para.Range.Text.TrimEnd([char]13, [char]7, ' ') | |
| # Falls ListString vorhanden, steht die Nummer oft schon im Text vorne – deduplizieren | |
| $displayText = $rawText | |
| if ($numberText -and $rawText.StartsWith($numberText)) { | |
| $displayText = $rawText.Substring($numberText.Length).TrimStart(' ', "`t") | |
| } | |
| # Einrückung nach Level | |
| $indent = " " * ($level - 1) | |
| # Zusammenbauen: Nummer + Text | |
| $entry = if ($numberText) { | |
| "{0}{1} {2}" -f $indent, $numberText, $displayText | |
| } else { | |
| "{0}{1}" -f $indent, $displayText | |
| } | |
| [void]$toc.Add([PSCustomObject]@{ | |
| Level = $level | |
| Number = $numberText | |
| Text = $displayText | |
| StyleName = $styleId | |
| Formatted = $entry | |
| }) | |
| } | |
| # Ausgabe | |
| foreach ($h in $toc) { | |
| Write-Host $h.Formatted | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment