Counting total number of pages across multiple PDF files on the Windows' Powershell

0

1

I'm trying to write a single script on the Windows' Powershell so I can know the total number of pages across various pdf files in the same directory. However, I'm not getting the intended results. Here's my script:

$files = l .
$result = 0
for ($i=0; $i -lt $files.Count; $i++) 
{
    $fileName = $files[$i].FullName
    if ($fileName.EndsWith(".pdf"))
    {
         pdfinfo.exe $fileName | findstr.exe "Pages:*" | awk '{$result += $2} {print $result}'
    }
}

Current results (Individual number of pages):

20 
19 
10 
16 
18 
14 
9  
29 
24 
28 
16 
30 
32 
21 
13 
17

Expected results:

20
39
49
65
83
...
...
...
316

Or just the final value:

316

136

Posted 2019-06-07T19:27:29.830

Reputation: 3

Answers

0

Just to make clear pdfinfo isn't a tool which comes with Windows/PowerShell
Windows ports can be downloaded from several sources, one is
https://xpdfreader-dl.s3.amazonaws.com/xpdf-tools-win-4.01.01.zip

If using PowerShell I'd stay with it as much as possible:

## Q:\Test\2019\06\07\SO_1446208.ps1

$folder = 'C:\Test'
$Total = $Files = 0

foreach($File in (Get-ChildItem -Path $Folder -Filter *.pdf)){
    $Pages = (pdfinfo $File.FullName | Select-String -Pattern '(?<=Pages:\s*)\d+').Matches.Value
    $Total += $Pages
    $Files++
    [PSCustomObject]@{
        PdfFile = $File.Name
        Pages   = $Pages
    }
}
"`nTotalNumber of pages: {0} in {1} files" -f $Total,$Files

Sample output (the whole [PSCustomObject] just for reference)

> Q:\Test\2019\06\07\SO_1446208.ps1

PdfFile                      Pages
-------                      -----
2014-02-25_Allwinner A80.pdf 1
test.pdf                     4

TotalNumber of pages: 5 in 2 files

LotPings

Posted 2019-06-07T19:27:29.830

Reputation: 6 150

Thank you very much! I'm not very familiar with the powershell syntax, so I would still like to know why my version isn't working – 136 – 2019-06-08T00:03:53.047

I think awk '{$result += $2} will append strings, and not do an addition. – LotPings – 2019-06-08T00:18:21.837