Reputation: 666
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();
Upvotes: 0
Views: 2764
Reputation: 3791
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.
Upvotes: 1