How to copy a paragraphs format in MS-Word and use it on another paragraph by a PowerShell script?

47 Views Asked by At

I'm writing a script which should create a new word document based on a template. Users can configure, which chapters of the template document they want to include in their new document. This selection is made in Excel and will be read out by my script. This part works well, no problem. But when iterating through the selected chapters I use a function to search the template doc for a chapter and, if found, copy the heading and the following text to the new document. But I don't just need to copy the letters, but also the built-in format of the text. Headings can range from "heading 1" to "heading 4", the text itself is always standard text body. But i'm not able to copy the format of the source document correctly.

My function looks like this:

function searchAndCopy {
    param (
        $chapterName
    )

    for ($i = 1; $i -lt $paras.Count - 1; $i++) {
        $para = $paras[$i]
        
        if ($paras[$i+1]) {
            $nextPara = $paras[$i+1]
        } else {
            $nextPara = NULL
        }

        if ($chapterName.Trim() -eq ($para.Range.Text).Trim()) {
            Write-Output "Chapter found"
            $heading = $para.Range.Text
            $styleName = $para.Style.NameLocal

            Write-Output "Heading: $heading"
            Write-Output "Style: $styleName"
            
            if ($nextPara) {
            $content = $nextPara.Range.Text
            Write-Output "Text: $content"
            }
        }
    }

    $newParagraph = $document.Paragraphs.Add()
    $newParagraph.Range.Style = $styleName
    $newParagraph.Range.Text = $heading

    $contentParagraph = $document.Paragraphs.Add()
    $contentParagraph.Range.Text = $content
    $document.SaveAs("C:\...")
}

I tried different ways of assigning the style and also receiving the style in the source document, not just by "NameLocal". But this solution is the best I got so far - the paragraphs in the new document show up in the correct font size, color, etc. in the new document. But the problem is now: Word doesnt recognize the copiped paragraph as being in e.g. "heading 2" style. It looks like it, but Word says it is standard text. I tried several ways but now i'm out of ideas.

Thank you for your help!

0

There are 0 best solutions below