简体   繁体   中英

Powershell - counting characters in Word documents - including headers and footers

I need to count the number of characters in a word document including the characters in the headers and footers. I can successfully count the number of chars in the main document, thanks to the help I got here: Powershell How to get character count at word document? but I have not succeeded in finding how to get to the headers and footers. Any ideas? Thanks a lot in advance for any help.

You can access both the Headers and the Footers from the Document.Sections property. There are different headers/footers for primary, first page, and even pages so we loop through each with ForEach-Object (shown below with alias '%'), trim any whitespace off the end and filter out any that are only whitespace.

$word = New-Object -ComObject 'Word.Application'
$doc = $word.Documents.Open('C:\temp\powershell\wordcount.docm')

& {
    $doc.Content.Text.TrimEnd()

    $doc.Sections | % Headers | % Range | % Text | % TrimEnd | ? {-not [string]::IsNullOrWhiteSpace($_)} 

    $doc.Sections | % Footers | % Range | % Text | % TrimEnd | ? {-not [string]::IsNullOrWhiteSpace($_)} 

} | Measure-Object length -Sum | ForEach-Object Sum

$doc.Close()
$word.Quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM