Powershell-计算Word文档中的字符数,包括页眉和页脚



我需要计算word文档中的字符数,包括页眉和页脚中的字符。多亏了这里的帮助,我可以成功地计算出主文档中的字符数:Powershell如何在word文档中获取字符数?但我还没有成功地找到如何获取页眉和页脚。有什么想法吗?事先非常感谢您的帮助。

编辑:

下面的代码循环遍历word文档的页眉和页脚,但我似乎无法获取它们的大小。

Add-Type -AssemblyName System.Windows.Forms
$browser = New-Object System.Windows.Forms.FolderBrowserDialog
$null = $browser.ShowDialog()
$path = $browser.SelectedPath
Get-ChildItem $path -Recurse -File | 
Foreach-Object {
$Word = New-Object -comobject Word.Application
$filename = $_.FullName
$Word.Visible = $False
$datasheet = $word.Documents.Open($filename,$false, $true)
$Word.ActiveDocument.Content.Select()

foreach ($section in $datasheet.Sections)
{
ForEach ($header in $section.Headers)
{
#$header.Range.Fields.Update() | Out-Null
$NbHeader = $header.Range.Text.Count.ToString()
"header $NbHeader"
}
ForEach ($footer in $section.Footers)
{
#$footer.Range.Fields.Update() | Out-Null
$NbFooter = $footer.Range.Text.Count.ToString()
"footer $NbFooter"
}
}

$datasheet.close()
$word.Quit()
}
Read-Host -Prompt "Press Enter to exit"

您可以从Document.Sections属性访问Headers和Footers。主页、首页甚至偶数页都有不同的页眉/页脚,因此我们用ForEach-Object(如下别名"%"所示(循环遍历每一页,修剪末尾的任何空白,并过滤掉任何仅为空白的空白。

$word = New-Object -ComObject 'Word.Application'
$doc = $word.Documents.Open('C:tempword_count.docx', $null, $true)
& {
$doc.Paragraphs | % Range | % Text | % TrimEnd
$doc.Sections | % Headers | % Range | % Paragraphs | % Range | % Text | % TrimEnd | ? {-not [string]::IsNullOrWhiteSpace($_)} 
$doc.Sections | % Footers | % Range | % Paragraphs | % Range | % Text | % TrimEnd | ? {-not [string]::IsNullOrWhiteSpace($_)} 
} | Measure-Object length -Sum | ForEach-Object Sum
$doc.Close()
$word.Quit()

要测试并显示正在计数的内容,请尝试此

$word = New-Object -ComObject 'Word.Application'
$doc = $word.Documents.Open('C:tempwordcount.docx', $null, $true)
& {
$doc.Paragraphs | % Range | % Text | % TrimEnd
$doc.Sections | % Headers | % Range | % Paragraphs | % Range | % Text | % TrimEnd | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } 
$doc.Sections | % Footers | % Range | % Paragraphs | % Range | % Text | % TrimEnd | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } 
} | ForEach-Object -Begin {$tally = 0} {
[PSCustomObject]@{
Length = $_.length
Tally = $tally += $_.length
Text = $_
} 
} 
$doc.Close()
$word.Quit()

最新更新