Home > database >  How do I write a Windows 10 script to increment a counter by 1 each time a print job prints?
How do I write a Windows 10 script to increment a counter by 1 each time a print job prints?

Time:06-15

I'd like to write a script for Windows 10 to add 1 to a count in a .txt each time a print job completes. Ideally a separate count for each day, so I can see how many print jobs were completed in a day.

Any help in understanding how to go about this is appreciated!

CodePudding user response:

The print service already logs every time it prints - you just need to enable the appropriate event log channel and consume the resulting log events:

# Enable the Microsoft-Windows-PrintService/Operational log channel
wevtutil.exe set-log Microsoft-Windows-PrintService/Operational /enabled:true

Now that the log channel is enabled, the print service will log an event with event ID 307 everytime it executes a local print job. Since the log events all have timestamps, getting a count per day is as simple as using the Group-Object cmdlet:

# Fetch the print job events from the event log
$printJobEvents = Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-PrintService/Operational'; EventId=307 } 

# Group by date logged, to get a count-per-day
$printJobEvents |Group-Object { '{0:yyyy-MM-dd}' -f  $_.TimeCreated.Date } -NoElement |Sort-Object Name

CodePudding user response:

One technique that might be useful is to query stats for the spooler service like this:

Get-CimInstance 'Win32_PerfFormattedData_Spooler_PrintQueue' |
    Format-Table -Property Name,Jobs,TotalJobsPrinted,TotalPagesPrinted -AutoSize

This gives output like this:

Name                          Jobs TotalJobsPrinted TotalPagesPrinted
----                          ---- ---------------- -----------------
Printer1                         0               50               212
Printer2                         3               13               118
Printer3                         1               33               306
_Total                           4               96               636

The stats are reset each time the Print Spooler service restarts, so you'll need to take that into account in your final script, which might make this a trickier option than Mathias' event log solution.

  • Related