0
votes

I don't seem to find quite a bit of examples of PowerShell and Microsoft Word. I've seen plenty of how to post a page number in a footer, but I don't quite grasp the PowerShell select method or object. An example of how to count up pages in any particular set of documents was also reviewed.

I've dug through quite a few books and only one of them really had anything to do with PowerShell and MS Word. If anything only a few trivial Excel examples or how to create a word document was given. I also noticed that Office 365 is offered as a focus point of one book and even an online script building resource, but nothing like that I could find on Office 2013 and prior.

This is the script that I'm working with now which isn't really much to look at.

$objWord = New-Object -ComObject Word.Application;
$objWord.Visible = $false;
$objWord.DisplayAlerts = "wdAlertsNone";
# Create the selection object
$Selection = $objWord.Selection;
#$document = $objWord.documents.open("C:\Path\To\Word\Document\file.docx");
$hyperlinks = @($document.Hyperlinks);
#loop through all links in the word document     
$hyperlinks | ForEach {        
    if($_.Address -ne $null)
    {
        # The character number where the hyperlink text starts
        $startCharNumber = $_.Range.Start;
        # The character number where the hyperlink text ends
        $endCharNumber = $_.Range.End;
        # Here is where to calculate which page number the $startCharNumber is found on.  How exactly to do this?
        # For viewing purposes only.  To be used to create a report or index.
        Write-Host "Text To Display: " $_.TextToDisplay " URL: " $_.Address " Page Num: " ;
    }
}
$objWord.quit();
1
Just a note, $_.Range.Start is the character number, not the line number. .End is the same case.TheMadTechnician
@TheMadTechnician Thanks, I'll correct the variable and comments so its correct. I knew this, but labeled it as I thought about it. Funny how thoughts get typed and miss review :)Sn3akyP3t3

1 Answers

1
votes

You can use Information(wdActiveEndPageNumber) to get the page containing the selection.

$word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Word.Application')
$wdActiveEndPageNumber = 3
$doc = $word.ActiveDocument

foreach ($h in $doc.Hyperlinks) {
    $page = $h.Range.Information($wdActiveEndPageNumber)
    echo "Page $page : $($h.Address)" 
}

Edited following @bibadia's comment.