Search code examples
powershellbookmarks

how to create bookmark in word using powershell


I have to create bookmark in the word document, but don't understand how to set define a range

$Word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
$Selection = $Word.Selection
$Selection.TypeParagraph()
$Selection.Style =$Title
$Selection.TypeText($someText2)
$Selection.TypeParagraph()
$doc.Bookmarks.Add($bN,???)"

I want to add some text to my document and then make this text as bookmark. What is the best way to do it? Thank you/


Solution

  • I'm not 100% sure what you are attempting to do, but this may work for what you are attempting to do:

    $someText2 = "Some text to add"
    
    #Open Active Word Document    
    $Word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
    $Selection = $Word.Selection
    $Selection.TypeParagraph()
    $Selection.Style = "Title"
    $selection.TypeText("This is the Title")
    $Selection.TypeParagraph()
    
    #Add the bookmark to the Selection
    $Selection.Bookmarks.Add("Bookmark1")
    #Load the bookmark from the Selection
    $bookmark = $Selection.Bookmarks._NewEnum | Where-Object {$_.Name -eq "Bookmark1"}
    #add the text to the selection
    $Selection.TypeText($someText2)
    #set the end of the bookmark to the length of the added text
    $bookmark.End = $bookmark.End + $someText2.Length
    

    UPD

    $Word = New-Object -ComObject Word.Application
    $Word.Visible = $True
    $Document = $Word.Documents.Add()
    $Selection = $Word.Selection
    $Selection.TypeText($someText)
    $Selection.TypeParagraph()
    
    $Word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
    $Selection = $Word.Selection
    $Selection.Bookmarks.Add($bN)
    $bookmark = $Selection.Bookmarks._NewEnum | Where-Object {$_.Name -eq $bN}
    $Selection.TypeText($someText2)
    $bookmark.End = $bookmark.End + $someText2.Length