我似乎找不到很多关于PowerShell和Microsoft Word的例子。我已经看过很多关于如何在页脚中发布页码的内容,但是我还没有完全掌握PowerShell的选择方法或对象。还回顾了一个如何计算任何特定文档中页数的示例。
我翻了很多书,只有一本真正与PowerShell和MS Word有关。如果有的话,只给出了几个简单的Excel示例或如何创建word文档。我还注意到,Office 365是一本书的重点,甚至是一个在线脚本构建资源,但我在Office 2013及之前的版本中找不到类似的内容。
这是我现在正在使用的脚本,它不是很好看。
$objWord = New-Object -ComObject Word.Application;
$objWord.Visible = $false;
$objWord.DisplayAlerts = "wdAlertsNone";
# Create the selection object
$Selection = $objWord.Selection;
#$document = $objWord.documents.open("C:PathToWordDocumentfile.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();
您可以使用Information(wdActiveEndPageNumber)
获取包含所选内容的页面。
$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)"
}
根据@bibadia的评论编辑。